How to add a UI control to an ItemRenderer component
Using a DisplayObjectRecycler
, an ItemRenderer
component may be customized to display a UI control as an accessory view.
Create the ListView
To start, create a ListView
component and pass it a data collection containing some items.
var listView = new ListView();
listView.dataProvider = new ArrayCollection([
{ name: "Volume", accessory: new HSlider() },
{ name: "Enable Music", accessory: new ToggleSwitch() }
]);
listView.itemToText = item -> item.name;
addChild(listView);
The techniques used in this tutorial apply to an
ItemRenderer
used in any data container — not justListView
. The code shouldn't require more than trivial tweaks for other containers, such asGridView
orGroupListView
.Similarly, you should be able to use the same capabilities with
HierarchicalItemRenderer
in containers likeTreeView
orTreeGridView
.
The itemToText
function makes it easy to populate the item renderer's text, but how to display the UI controls stored by the accessory
property?
Create the ItemRenderer
By using a DisplayObjectRecycler
, we can customize the default ItemRenderer
component to display both text and assets.
Call DisplayObjectRecycler.withClass()
to create an item renderer.
var recycler = DisplayObjectRecycler.withClass(ItemRenderer);
listView.itemRendererRecycler = recycler;
We don't add the accessory view yet because the creation function doesn't have access to any items from the list view's data provider. That data becomes available later, in the recycler's update
function.
Set the accessoryView
of the ItemRenderer
In the recycler's update
function, we have access to a ListViewItemState
object that contains all of the data that we need to populate the item renderer, including the item from the data provider that is storing the UI control.
recycler.update = (itemRenderer:ItemRenderer, state:ListViewItemState) -> {
itemRenderer.text = state.text;
var accessoryView = cast(state.data.accessory, DisplayObject);
itemRenderer.accessoryView = accessoryView;
};
Use the ListViewItemState.data
property to access the item from the data provider. Then, pass the UI control to the accessoryView
property of the item renderer.
Be sure to set the item renderer's
text
property too. When you provide a recycler with a customupdate
function, the text is no longer populated automatically.