Jul 12

在前面的Flex中如何重新设置DataGrid控件的排序的例子Flex中如何创建自定义排序DataGrid控件的例子等例子(右上角搜索)中,都演示了排序相关的问题,接下来的例子演示了Flex中利用SortField和Sort类,对ArrayCollection进行排序。

让我们先来看一下Demo(可以右键View Source或点击这里察看源代码):


下面是完整代码(或点击这里察看):

Download: main.mxml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="init()">
  3.  
  4.     <mx:Script>
  5.         <![CDATA[
  6.             import mx.collections.SortField;
  7.             import mx.collections.Sort;
  8.             import mx.collections.ArrayCollection;
  9.  
  10.             [Bindable]
  11.             private var arrColl:ArrayCollection;
  12.  
  13.             /** This method gets called by the main mx:Application tag and initializes/populates the ArrayCollection object with a bunch of random numbers. */
  14.             private function init():void {
  15.                 var i:int;
  16.  
  17.                 /* Initialize and populate the ArrayCollection object. */
  18.                 arrColl = new ArrayCollection();
  19.                 for (i = 0; i < 20; i++) {
  20.                     arrColl.addItem({data:getRandomNumber().toFixed(4)});
  21.                 }
  22.             }
  23.  
  24.             /** This method returns a random floating-point number between 0 and 10000. */
  25.             private function getRandomNumber():Number {
  26.                 return Math.random() * 10000;
  27.             }
  28.  
  29.             /** This method gets called by the Button control's click handler and creates a new SortField and Sort object which are used to sort the ArrayCollection. */
  30.             private function button_click():void {
  31.                 /* Create the SortField object for the "data" field in the ArrayCollection object, and make sure we do a numeric sort. */
  32.                 var dataSortField:SortField = new SortField();
  33.                 dataSortField.name = "data";
  34.                 dataSortField.numeric = true;
  35.  
  36.                 /* Create the Sort object and add the SortField object created earlier to the array of fields to sort on. */
  37.                 var numericDataSort:Sort = new Sort();
  38.                 numericDataSort.fields = [dataSortField];
  39.  
  40.                 /* Set the ArrayCollection object's sort property to our custom sort, and refresh the ArrayCollection. */
  41.                 arrColl.sort = numericDataSort;
  42.                 arrColl.refresh();
  43.             }
  44.         ]]>
  45.     </mx:Script>
  46.  
  47.     <mx:List id="list" dataProvider="{arrColl}" textAlign="right" labelField="data" width="100" />
  48.  
  49.     <mx:Button id="button" label="sort items" click="button_click()" />
  50.  
  51. </mx:Application>
代码:Peter deHaan 翻译/整理/编译:minidxer

written by Minidxer  |  tags: , , , ,

Related Post

Leave a Reply