首页 > 设计 > WEB开发 > 正文

13.6.遍历集合对象并记录位置

2023-07-22 12:39:12
字体:
来源:转载
供稿:网友
13.6.1. 问题
我想双向遍历集合,并保持当前所在位置
13.6.2. 解决办法
使用ListViewCollection 类的createCursor 方法创建可前后移动的游标。
13.6.3. 讨论
可使用视图游标浏览集合数据视图中所有数据项,访问和修改集合数据。游标是一个位置指示器,它执行特定位置的数据项。你可以使用集合的createCursor 方法返回一个视图游标。

游标的各种方法和属性都由IViewCursor 接口定义。

通过IViewCursor 方法,你可以前后移动游标,用特定条件搜索数据项,获取指定位置的数据项,保存游标所在位置,以及添加,删除或修改数据值。

当你使用标准的Flex 集合类如ArrayCollection 和XMLListCollection 时,可直接使用IViewCursor 接口,不需要引用对象实例,例如:
+展开
-XML
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxmlwidth="400height="300creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.collections.SortField;
import mx.collections.Sort;
import mx.collections.IViewCursor;
import mx.collections.CursorBookmark;
import mx.collections.ArrayCollection;
[Bindable]
private var coll:ArrayCollection;
[Bindable]
private var cursor:IViewCursor;
private function init():void {
coll = new ArrayCollection([
{city:"Columbus", state:"Ohio", region:"East"},
{city:"Cleveland", state:"Ohio", region:"East"},
{city:"Sacramento", state:"California", region:"West"},
{city:"Atlanta",state:"Georgia", egion:"South"}]);
cursor = coll.createCursor();
}
//这个例子中,IViewCursor对象的findFirst方法根据文本框中的数据定位第一个匹配的集合数据:
Code View:
private function findRegion():void {
var sort:Sort = new Sort();
sort.fields = [new SortField("region")];
coll.sort = sort;
coll.refresh();
cursor.findFirst({region:regionInput.text});
}
private function findState():void {
var sort:Sort = new Sort();
sort.fields = [new SortField("state")];
coll.sort = sort;
coll.refresh();
cursor.findFirst({region:stateInput.text});
}

]]>
</mx:Script>
<mx:Label text="{cursor.current.city}"/>
<mx:Button click="cursor.moveNext()label="Next"/>
<mx:Button click="cursor.movePrevious()label="Previous"/>
<mx:HBox>
<mx:TextInput id="regionInput"/>
<mx:Button click="findRegion()label="find region"/>
</mx:HBox>
<mx:HBox>
<mx:TextInput id="stateInput"/>
<mx:Button click="findRegion()label="find state"/>
</mx:HBox>
</mx:VBox>

IViewCursor 接口定义了三个方法用于搜索集合:
findFirst(values:Object):Boolean
此方法查找集合中具有指定属性的第一个项目,并将光标定位到该项目

findLast(values:Object):Boolean
此方法查找集合中具有指定属性的最后一个项目,并将光标定位到该项目

findAny(values:Object):Boolean
此方法查找集合中具有指定属性的项目并将光标定位到该项目,这个是速度最快的方法。

注意这三个方法可工作在未排序的ArrayCollection 或XMLListCollection。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表