Actionscript/Flex: How to maintain the selected item (instead of index) after a Spark list sorts
I change an item in Spark List. The item then moves to a different index in the list since I keep the List's dataProvider sorted. Howeve开发者_高级运维r, the selectedIndex stays where the item used to be. I want the List's selectedIndex to still be on the item that changed. Has anybody solved this problem before or have any tips?
Thanks all, I finally solved this. For posterity, this is what I did:
In my Spark List subclass, I override set dataProvider, and attach a weak-referenced event listener to the dataProvider.
override public function set dataProvider(theDataProvider:IList):void
{
super.dataProvider = theDataProvider;
dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, onCollectionChange, false, 0, true);
}
Then, in the event handler, if the item that moved was previously selected, I reselect it. See the CollectionEventKind.MOVE
case.
private function onCollectionChange(theEvent:CollectionEvent):void
{
if (theEvent.kind == CollectionEventKind.ADD)
{
// Select the added item.
selectedIndex = theEvent.location;
}
else if (theEvent.kind == CollectionEventKind.REMOVE)
{
// Select the new item at the location of the removed item or select the new last item if the old last item was removed.
selectedIndex = Math.min(theEvent.location, dataProvider.length - 1);
}
else if (theEvent.kind == CollectionEventKind.MOVE)
{
// If the item that moved was selected, keep it selected at its new location.
if (selectedIndex == theEvent.oldLocation)
{
selectedIndex = theEvent.location;
}
}
}
精彩评论