天天看点

flex基础——分别用MXML、ActionScript初始化controls组件

一个Flex控件其实是一个AS类,它即可以在MXML里用基于标签的方式声明,也可以使用AS语句进行声明。

为了弄清我们该怎样使用一个控件,你首先得知道控件的公开的接口,即它的API,你需要知道有关控件的如下知识:

属性、方法、事件、样式、效果。你可以使用MXML初始化你的控件,我们称之为声明实例。你也可是使用 ActionScript3.0来初始化控件,我们叫它编程实例。

用MXML实现Label控件:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<s:Button id= "myButton" label="click me" />
	<s:Label text="Hello World" fontSize="18" fontWeight="bold" x="30" y="30" />
</s:Application>
           

用ActionScript实现Label控件:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
		<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			import spark.components.Label;
			protected var myActionScriptText:Label;
			protected function creationCompleteHandler(event:Event):void{  
				myActionScriptText = new Label();  
				myActionScriptText.text = "Hello World";  
				myActionScriptText.setStyle("fontSize", 18);  
				myActionScriptText.setStyle("fontWeight", "bold");   
				myActionScriptText.setLayoutBoundsPosition(30,30,true);
				this.contentGroup.addElement(myActionScriptText);
				
			}
		]]>
	</fx:Script>
	<s:Button id= "myButton" label="click me" 
			  click="creationCompleteHandler(event)">
	</s:Button>
</s:Application>
           

以上可以看出,两种语言实现了同样的作用,但是MXML却用了减少了很多行的代码。而ActionScript却可以重复利用其中的数据。其实各有千秋。