带排序的子元素结构体
public class ArrayCollectionSort
{/**
* @param sort1 主要排序字段
* @param sort2 辅助排序字段
*/
public function ArrayCollectionSort(sort1:int,sort2:Number)
{
_key_main=sort1;
_key_other=sort2;
}
private var _key_main:int;
private var _key_other:Number;
public function get key_other():Number
{
return _key_other;
}
public function get key_main():int
{
return _key_main;
}
public function toString():String
{
// TODO Auto Generated method stub
return "key_main:"+_key_main+",key_other"+_key_other;
}
}
列表管理类
public class ArrayCollectionSorts
{
public var list:ArrayCollection;
public function ArrayCollectionSorts()
{
list=new ArrayCollection();
var sort:Sort = new Sort();
sort.compareFunction = sortFunction;
list.sort = sort;
list.refresh();//调用ArrayCollection的refresh方法后的addItem才进行排序
}
/**
* @return -1,如果在已排序序列中 Object a 应显示在 Object b 之前。
* 0,如果 Object a 等于 Object b。
* 1,如果在已排序序列中 Object a 应显示在 Object b 之后。
*/
public function sortFunction(a:ArrayCollectionSort, b:ArrayCollectionSort, array:Array = null):int {
if(a.key_main>b.key_main){
return 1;
}else{
if(a.key_main<b.key_main){
return -1;
}else{
if(a.key_other>b.key_other){
return 1;
}else{
if(a.key_other<b.key_other){
return -1;
}else{
return 0
}
}
}
}
}
public function addItem(param:ArrayCollectionSort):void
{
// TODO Auto Generated method stub
list.addItem(param);
}
public function size():int
{
// TODO Auto Generated method stub
return list.length;
}
public function getItemAt(i:int):ArrayCollectionSort
{
// TODO Auto Generated method stub
return list.getItemAt(i) as ArrayCollectionSort;
}
public function refresh():void
{
// TODO Auto Generated method stub
list.refresh();
}
}
注意:
- 调用ArrayCollection的refresh方法后的addItem才进行排序
- 排序方法中if else 返回-1,1,0情况必须写全
测试类中方法
[Test]
public function sort():void
{
var list:ArrayCollectionSorts=new ArrayCollectionSorts();
list.addItem(new ArrayCollectionSort(1,1.0));
list.addItem(new ArrayCollectionSort(1,1.1));
list.addItem(new ArrayCollectionSort(2,1.0));
list.addItem(new ArrayCollectionSort(1,0.9));
list.addItem(new ArrayCollectionSort(2,0.9));
list.addItem(new ArrayCollectionSort(1,1.0));
list.addItem(new ArrayCollectionSort(0,1.0));
list.addItem(new ArrayCollectionSort(3,1.0));
}