Setting a default “selectedIndex” on an mx Control
This is the scenario I was faced with just the other day :

User is presented with your stock standard image gallery, only this time I had to write it all in Flex / AS3. Simple enough really, until I got stuck on a rather silly issue. It took me quite some time to find the solution and even then, I’m not quite satisfied with it – especially seeing as I’m making use of the Mate framework in this instance.
Ok, so on your right is a TileList of thumbnails. When the user clicks on a thumbnail, the larger version of the image is promptly displayed in a VBox on the left. Pretty straightforward stuff.
Now – when the app first loads, what I needed to do was display the first thumbnail’s “larger version” in the VBox by default – otherwise it looks empty and a little unprofessional. Still easy – all we need to do is execute a function when the TileList’s “onCreationComplete” event fires. All this function needs to do is set the TileList dataProvider’s selectedIndex to 0 ( as it’s blank by default ).
But what happens when the user performs a search ( chooses another category/album ) and the dataProvider’s content is replaced with a new ArrayCollection ? The selectedIndex gets reset to null of course and your “larger image” disappears.
This is where I got stuck – and I tried all sorts of things after finding out that the “dataChange” event doesn’t work. The problem wasn’t finding out when the ArrayCollection was replaced – the problem was setting the TileList dataProvider’s selectedIndex from within an “outside” class. I still don’t know how to do so unfortunately – so if you’re reading this and know of a better way to solve this problem, please feel free to leave a comment – and just write my stupidity off to “Flex Noobness”.
In the end I found that the “updateCompleted” event for the TileList fires when the dataProvider’s contents gets replaced. So what I ended up with is the following code, which I hope will help someone else in a similar predicament.
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:model="com.gallery.model.*" xmlns:viewUtils="com.asfusion.mate.viewUtils.*" xmlns:controls="qs.controls.*"> <mx:Script> <![CDATA[ import com.gallery.events.*; import mx.collections.ArrayCollection; public function setItemDefault() : void{ if (!list.selectedItem && model.currentSet != null && model.currentSet.length > 0){ list.selectedIndex = 0; } } ]]> </mx:Script> <model:PhotoViewerModel id="model" /> <mx:TileList id="list" direction="horizontal" dataProvider="{model.currentSet}" itemRenderer="com.gallery.ui.renderers.Thumbnail" width="100%" height="100%" updateComplete="{setItemDefault()}"/> </mx:VBox>
