Jul 12
在前面的Flex中如何重新设置DataGrid控件的排序的例子,Flex中如何创建自定义排序DataGrid控件的例子等例子(右上角搜索)中,都演示了排序相关的问题,接下来的例子演示了Flex中利用SortField和Sort类,对ArrayCollection进行排序。
让我们先来看一下Demo(可以右键View Source或点击这里察看源代码):
下面是完整代码(或点击这里察看):
Download: main.mxml
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="init()">
- <mx:Script>
- <![CDATA[
- import mx.collections.SortField;
- import mx.collections.Sort;
- import mx.collections.ArrayCollection;
- [Bindable]
- private var arrColl:ArrayCollection;
- /** This method gets called by the main mx:Application tag and initializes/populates the ArrayCollection object with a bunch of random numbers. */
- private function init():void {
- var i:int;
- /* Initialize and populate the ArrayCollection object. */
- arrColl = new ArrayCollection();
- for (i = 0; i < 20; i++) {
- arrColl.addItem({data:getRandomNumber().toFixed(4)});
- }
- }
- /** This method returns a random floating-point number between 0 and 10000. */
- private function getRandomNumber():Number {
- return Math.random() * 10000;
- }
- /** 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. */
- private function button_click():void {
- /* Create the SortField object for the "data" field in the ArrayCollection object, and make sure we do a numeric sort. */
- var dataSortField:SortField = new SortField();
- dataSortField.name = "data";
- dataSortField.numeric = true;
- /* Create the Sort object and add the SortField object created earlier to the array of fields to sort on. */
- var numericDataSort:Sort = new Sort();
- numericDataSort.fields = [dataSortField];
- /* Set the ArrayCollection object's sort property to our custom sort, and refresh the ArrayCollection. */
- arrColl.sort = numericDataSort;
- arrColl.refresh();
- }
- ]]>
- </mx:Script>
- <mx:List id="list" dataProvider="{arrColl}" textAlign="right" labelField="data" width="100" />
- <mx:Button id="button" label="sort items" click="button_click()" />
- </mx:Application>
代码:Peter deHaan 翻译/整理/编译:minidxer
