How to display an image from a URL in an ItemRenderer component
Using a DisplayObjectRecycler
, an ItemRenderer
component may be customized with an AssetLoader
to display an image loaded from a URL.
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: "Pizza", iconURL: "https://example.com/img/pizza.png" },
{ name: "Cheeseburger", iconURL: "https://example.com/img/burger.png" },
{ name: "French Fries", iconURL: "https://example.com/img/fries.png" }
]);
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 URLs stored by the iconURL
property?
Create the ItemRenderer
and AssetLoader
By using a DisplayObjectRecycler
, we can customize the default ItemRenderer
component to display both text and images.
Call DisplayObjectRecycler.withFunction()
to create an item renderer and pass an AssetLoader
to the item renderer's icon
property.
var recycler = DisplayObjectRecycler.withFunction(() -> {
var itemRenderer = new ItemRenderer();
itemRenderer.icon = new AssetLoader();
return itemRenderer;
});
listView.itemRendererRecycler = recycler;
We don't populate the source
property of the AssetLoader
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 source
of the AssetLoader
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 image's URL.
recycler.update = (itemRenderer:ItemRenderer, state:ListViewItemState) -> {
itemRenderer.text = state.text;
var loader = cast(itemRenderer.icon, AssetLoader);
loader.source = state.data.iconURL;
};
To access the AssetLoader
that we created in DisplayObjectRecycler.withFunction()
, cast the icon
property. Then, use the data
property of the ListViewItemState
to get the item from the data provider, which has our iconURL
property.
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.