Prevent selection of a particular item in spark li

2019-07-21 01:33发布

问题:

I have a Spark List which has a custom itemRenderer for rendering each item in the List. I wish to prevent an item in that list from being selected (based on some custom logic) by the user.

What is the best way I can achieve this?

Here's how my List is defined:

<s:List id="myList" itemRenderer="com.sample.MyItemRenderer" />

and of course, I have a item renderer defined as the class com.sample.MyItemRenderer.

回答1:

The selection of items is handled by the list alone as far as I know, so I would say that you can manage it from there. I would have a field on the Objects that are in the list called "selectable" or something like that and when the list item is changing check to see if the new item is actually selectable and if it isn't then you can either have it clear the selection or reset to the previous selection. You can accomplish that by reacting to the "changing" event on the list component and calling "preventDefault" on the IndexChangeEvent as follows:

protected function myList_changingHandler(event:IndexChangeEvent):void {
    var newItem:MyObject = myList.dataProvider.getItemAt(event.newIndex) as MyObject;
    if(!newItem.selectable) {
        event.preventDefault();
    }
}

// Jumping ahead ...

<s:List id="myList" changing="myList_changingHandler(event)" // ... continue implementation

The relevant part of the MyObject class is as follows:

public class MyObject {

    private var _selectable:Boolean;

    public function MyObject(){

    }

    public function set selectable(value:Boolean):void {
        _selectable = value;
    }

    public function get selectable():Boolean {
        return _selectable;
    }
}