-
1 <?xml version="1.0" encoding="utf-8"?> 2 <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 3 xmlns:s="library://ns.adobe.com/flex/spark" 4 xmlns:mx="library://ns.adobe.com/flex/mx" 5 minWidth="955" minHeight="600" 6 creationComplete="init()"> 7 8 <fx:Script> 9 <![CDATA[ 10 import mx.events.FlexEvent; 11 import mx.utils.StringUtil; 12 13 import spark.events.TextOperationEvent; 14 15 public var listshow:XML= 16 <apps name="计算机课程"> 17 <item name="算法与数据结构"/> 18 <item name="分布式计算"/> 19 <item name="计算机网络"/> 20 <item name="分布式系统"/> 21 </apps>; 22 [Bindable] 23 public var listnew:XML=null; //搜索过滤后的数据 24 25 public function init():void 26 { 27 getData(); 28 } 29 protected function textinput_change(event:TextOperationEvent):void 30 { 31 getData(); 32 } 33 protected function getData():void 34 { 35 //删除字符串的开头末尾的空格 36 if(StringUtil.trim(textinput.text)=="") 37 { 38 listnew=listshow; 39 }else{ 40 createNewXML(textinput.text,listshow); 41 } 42 //打开或关闭指定项目下的所有树项目。如果设置 dataProvider 之后立即调用 expandChildrenOf() 43 //则您可能看不到正确的行为。您应该等待对组件进行验证或调用 validateNow()方法 44 tree.validateNow(); 45 expandtree(); 46 } 47 //搜索过滤产生新的XML 48 private function createNewXML(str:String,xml:XML):void 49 { 50 listnew=<apps name="计算机课程" />; 51 for(var i:int=0;i<xml.children().length();i++) 52 { 53 var itemxml:XML=xml.child("item")[i]; 54 if(isInStr(str,itemxml.@name.toString())) 55 listnew.appendChild(itemxml); 56 } 57 } 58 //判断search_str是否在str中 59 public function isInStr(search_str:String,str:String):Boolean 60 { 61 var num:int=str.indexOf(search_str); 62 if(num>-1) 63 { 64 return true; 65 }else return false; 66 } 67 protected function expandtree():void 68 { 69 for each(var itemxml in this.tree.dataProvider) 70 this.tree.expandChildrenOf(itemxml,true); 71 } 72 ]]> 73 </fx:Script> 74 <s:Panel width="767" height="361" title="演示实例"> 75 <s:TextInput id="textinput" x="10" y="10" width="174" height="32" 76 change="textinput_change(event)" prompt="请输入要搜索的关键词"/> 77 <mx:Tree id="tree" x="10" y="50" width="174" height="208" dataProvider="{listnew}" 78 labelField="@name"/> 79 <s:Label x="14" y="263" height="28" text="更多例子 请关注:www.baidu.com"/> 80 </s:Panel> 81 </s:Application>
效果图:
搜索结果: