4
votes

In Flex I can create an ItemRenderer to represent each item in the Lists DataProvider but how do I access the instance of the ItemRenderer via the DataProviders Object? Something like myList.getItemRenderer(dp.getItemAt(10));

4
Since a Flex list recycles its item renderers by default, you won't be able to reliably access an item renderer for a given data object. There might not even be a renderer associated with the data object if it is scrolled outside of the viewable area of the list. What is it you are trying to accomplish?Wade Mueller

4 Answers

15
votes
public function getItemRenderer(list:List, item:Object):ItemRenderer
{
    var dataGroup:DataGroup = list.dataGroup;
    var n:int = dataGroup.numElements;
    for (var i:int = 0; i < n; i++)
    {
        var renderer:ItemRenderer = dataGroup.getElementAt(i) as ItemRenderer;
        if (renderer && renderer.data == item)
            return renderer;
    }
    return null;
}
1
votes

By using this method, you cannot get the renderer that is outside of the viewable area and there will also be a lot of other issues.

1
votes

If you need to change how the item renderer is behaving, change the data that is causing the behavior.

var items:ArrayCollection = this.dataProvider as ArrayCollection;
    var newItems:ArrayCollection = new ArrayCollection();
    if (items.length > 0) {
        for (var i:int = 0; i < items.length; i++) {
            var item:Object = items[i] as Object;

            if (!item.editMode) {
                item.editMode = true;
            } else {
                item.editMode = false;
            }

            newItems.addItem(item);
        }
    }

    this.dataProvider = null;
    this.dataProvider = newItems;

This is a simple example where the I mark items to be deletable and the renderer changes according since the data has been changed. For larger data sets, I understand this can be a little slow but it gives you the control you are after.

If you need to change one renderer, simply modify the data on the corresponding object in the dataProvider or dataGroup.

var item:Object = this.getItemAt(index);
1
votes

I know this is an old thread, but perhaps it will help someone:

var item:ItemRenderer = list.dataGroup.getElementAt(0) as ItemRenderer;

That will give you the ItemRenderer, if you have a custom IR then just use that class and cast and your set.