Flex有两个阵营组件:spark组件和mx组件,关于spark组件和mx组件的区别,spark组件具体有哪些?mx组件具体有哪些?大家请参考adobe的其它文档。
本文旨在遍历容器的组件,其可以是遍历Application的所有组件,也可以遍历Group、Box中包含的组件等等。
遍历组件需要做2件事情:
1)区别是spark组件还是mx组件,因为spark组件和mx组件加载子元素处理方式不同,spark组件通过addElement来加载子元素,而mx则是addChild来加载子元素;
2)区别是否为容器(container)还是普通的组件(component);
下述为一个遍历组建的简单demo,当然代码可以继续优化。
<?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" width="600" height="261">
<s:layout> <s:BasicLayout/> </s:layout>
<fx:Script> <![CDATA[ import spark.components.supportClasses.SkinnableComponent; private var result:String = "";
protected function btnRetrieve_clickHandler(event:MouseEvent):void { result = ""; retrieve(this,""); txtResult.text = result; }
private function retrieve(obj:Object, prefix:String):void{ if(obj is SkinnableComponent){ result +=prefix+obj["id"]+"\r\n"; var nums:int = 0; if(obj.hasOwnProperty("numElements")) nums = obj.numElements; for(var i:int = 0; i<nums; i++){ var component:Object = obj.getElementAt(i); retrieve(component,prefix+"--"); } }else{ result+=prefix+obj["id"]+"\r\n"; var nums:int = 0; if(obj.hasOwnProperty("numChildren")) nums = obj.numChildren; for(var i:int = 0; i<nums; i++){ var component:Object = obj.getChildAt(i); retrieve(component,prefix+"--"); } } } ]]> </fx:Script>
<s:Panel id="sPanel" title="Spark Panel" width="414"> <s:TextInput x="10" y="32" id="sPanel_textinput"/> <s:Button x="199" y="32" label="按钮" id="sPanel_button"/>
</s:Panel> <mx:Panel id="mPanel" title = "MX Panel" x="0" y="135" width="414" height="116" layout="absolute"> <s:TextInput x="10" y="15" id="mPanel_textinput"/> <s:Button label="按钮" x="200" y="16" id="mPanel_button"/> </mx:Panel> <s:Button x="519" y="10" label="遍历控件" id="btnRetrieve" click="btnRetrieve_clickHandler(event)"/> <s:TextArea x="422" y="39" height="212" width="168" id="txtResult"/> </s:Application> |