Сортировка XMLListCollection - PullRequest
0 голосов
/ 29 марта 2012

Я пытался отсортировать XMLListCollection, следуя инструкциям, таким как this , в течение некоторого времени, но безуспешно.Вот соответствующий код:

<fx:Declarations>
<s:HTTPService id="photoServ" url="pics.xml" resultFormat="e4x"/>
<s:XMLListCollection id="photoList" source = "{photoServ.lastResult.photo}"/>
</fx:Declarations>

<s:List id="imageList" dataProvider="{photoList}" />

Моя цель состоит в том, чтобы отсортировать следующий xml-файл по местоположению вместо использования всего XMLListCollection в качестве dataProvider Списка на основе входной переменной местоположения.

Pics.XML

<photos>
<photo title="Picture 1" location="Canada" medium="Photograph" thumb="images/thumbs/Picture1.png" image="images/Picture1.png"/>
<photo title="Picture 2" location="UK" medium="Photograph" thumb="images/thumbs/Picture2.png" image="images/Picture2.png"/>
<photo title="Picture 3" location="USA" medium="Photograph" thumb="images/thumbs/Picture3.png" image="images/Picture3.png"/>
<photo title="Picture 4" location="Canada" medium="Photograph" thumb="images/thumbs/Picture4.png" image="images/Picture4.png"/>
<photo title="Picture 5" location="USA" medium="Photograph" thumb="images/thumbs/Picture5.png" image="images/Picture5.png"/>
<photo title="Picture 6" location="UK" medium="Photograph" thumb="images/thumbs/Picture6.png" image="images/Picture6.png"/>
</photos>

Любая и вся помощь приветствуется, чтобы получить это отсортировано.

РЕДАКТИРОВАТЬ

Это для фотогалереи, и я хочу иметь возможность показывать изображения в зависимости от местоположения - в данном случае Канада, США, Великобритания и т. Д. Спасибо за ввод!

Ответы [ 2 ]

2 голосов
/ 29 марта 2012

Вам просто нужно сделать

photoList.(@location=="Canada" || @location=="USA");

, чтобы получить список <photo> тегов с указанием местоположения в Канаде или США

Подумав, вы захотите установить xmlListCollectionas

photoList=new XMLListCollection(photoServ.lastResult.photo.(@location=="Canada" || @location=="USA"));

EDIT

Чтобы добавить код для разных местоположений, предположим, что у вас уже есть DropDownList, заполненный массивом местоположений.Предполагая, что ваш массив местоположений будет иметь вид

var locs:ArrayCollection=new ArrayCollection(["USA", "UK", "Canada", /*and others too*/]);

, а ваш DropDownList (давайте назовем его locationList) имеет dataProvider как locs

Теперь, когда вы хотитефильтр на месте, все, что вам нужно сделать, это

var lns:Vector.<Object>=locationList.selectedItems;
var filtered:XMLList=photoServ.lastResult.photo.(lns.indexOf(@location) != -1);
var photoList=new XMLListCollection(filtered);
0 голосов
/ 16 апреля 2012

ArrayCollection и XMLListCollection ведут себя очень похожим образом. XMLListCollection имеет свойства filterfunction и sort, с помощью которых фильтрация и сортировка коллекции могут быть простыми.

    <mx:Script>
        <![CDATA[
            import mx.collections.SortField;
            import mx.collections.Sort;
            import mx.collections.ArrayCollection;

            [Bindable]
            private var _photoXML:XML =
                        <photos>
                            <photo title="Picture 1" location="Canada" medium="Photograph" thumb="assets/images/thumbs/Picture1.jpg" image="assets/images/Picture1.jpg"/>
                            <photo title="Picture 2" location="UK" medium="Photograph" thumb="assets/images/thumbs/Picture2.jpg" image="assets/images/Picture2.jpg"/>
                            <photo title="Picture 3" location="USA" medium="Photograph" thumb="assets/images/thumbs/Picture3.jpg" image="assets/images/Picture3.jpg"/>
                            <photo title="Picture 4" location="Canada" medium="Photograph" thumb="assets/images/thumbs/Picture4.jpg" image="assets/images/Picture4.jpg"/>
                            <photo title="Picture 5" location="USA" medium="Photograph" thumb="assets/images/thumbs/Picture5.jpg" image="assets/images/Picture5.jpg"/>
                            <photo title="Picture 6" location="UK" medium="Photograph" thumb="assets/images/thumbs/Picture6.jpg" image="assets/images/Picture6.jpg"/>
                            <photo title="Picture 7" location="Canada" medium="Photograph" thumb="assets/images/thumbs/Picture2.jpg" image="assets/images/Picture1.jpg"/>
                            <photo title="Picture 8" location="UK" medium="Photograph" thumb="assets/images/thumbs/Picture3.jpg" image="assets/images/Picture2.jpg"/>
                            <photo title="Picture 9" location="Canada" medium="Photograph" thumb="assets/images/thumbs/Picture6.jpg" image="assets/images/Picture4.jpg"/>
                            <photo title="Picture 10" location="UK" medium="Photograph" thumb="assets/images/thumbs/Picture4.jpg" image="assets/images/Picture6.jpg"/>
                        </photos> ;

            [Bindable] 
            private var _countryCollection:ArrayCollection = new ArrayCollection(["select country","USA", "UK", "Canada"])

            private function filterByLocation(event:Event):void {
                if(countryCollection.selectedIndex > 0){
                    photoList.filterFunction = filter_ByLocation;
                    photoList.refresh();
                }else{
                    photoList.filterFunction = null;
                    photoList.refresh();
                }
            }

            private function filter_ByLocation(item:XML):Boolean {
                return item.@location == countryCollection.selectedItem;
            }

            private function sortByTitle():void {
                var titleSort:Sort = new Sort();
                    titleSort.fields = [new SortField('@location', true)];

                photoList.sort = titleSort;
                photoList.refresh();
            }

        ]]>
    </mx:Script>

    <mx:XMLListCollection id="photoList" source="{_photoXML.children()}"/>

    <mx:VBox width="100%" horizontalAlign="center">
        <mx:Image source="{imageList.selectedItem.@image}" width="800" height="400"/>
        <mx:HorizontalList id="imageList" dataProvider="{photoList}" labelField="@thumb" width="100%" height="100"
                           columnWidth="130" rowHeight="100" creationComplete="sortByTitle();">
            <mx:itemRenderer>
                <mx:Component>
                    <mx:Image source="{data.@thumb}"/>
                </mx:Component>
            </mx:itemRenderer>
        </mx:HorizontalList>    
    </mx:VBox>
    <mx:ComboBox id="countryCollection" dataProvider="{_countryCollection}" change="filterByLocation(event)"/>
</mx:Application>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...