Why won't SelectedIndex work every other time in Flex 4?
In the following working example the list's selected index is supposed to reset to 0 whenever the text box changes.
However, for some odd reason every other keystroke the selected item disappears and then reappears at the subsequent keystroke.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import mx.collections.ArrayList;
import mx.core.UIComponent;
import mx.events.FlexEvent;
import spark.effects.Scale;
import spark.events.TextOperationEvent;
[Bindable]
public var items : ArrayList;
protected function textinput1_changeHandler(event:TextOperationEvent):void
{
items = new ArrayList(input.text.split(" "));
list.selectedIndex = 0;
}
]]>
</fx:Script>
<s:TextInput x="165" y="124" change="textinput1_changeHandler(event)" id="input" text="a few words"/>
<s:Lis开发者_开发知识库t x="165" y="184" width="433" height="291" dataProvider="{items}" id="list"></s:List>
</s:Application>
First you should check "String.split" function. It has several bugs, I don't remember them. Try it on sequence like " " or "blah " (space at the end).
Also you should wait until the List is actually updated. Changing the bindable property only fires some event, not actually changing the list (AFAIK). Just google List's events. Also you may try to override List's "dataProvider" setter.
The problem is, that your list is not rendered yet, when you set the selected index.
Changing your textinput1_changeHandler
method will solve this issue:
protected function textinput1_changeHandler(event:TextOperationEvent):void
{
items = new ArrayList(input.text.split(" "));
callLater(function():void{list.selectedIndex = 0;});
}
Add into your function a refresh of the data provider first so it picks up the changes:
protected function textinput1_changeHandler(event:TextOperationEvent):void
{
items = new ArrayList(input.text.split(" "));
(list.dataProvider as ArrayCollection).refresh();
list.selectedIndex = 0;
}
The reason for the back and forth is that the event is only create with the index changes, check out listbase the setselectedindex;
the fix before you change selectedindex to 0 is to change it first to -1 and then to 0.
/**
* @private
* Used internally to specify whether the selectedIndex changed programmatically or due to
* user interaction.
*
* @param dispatchChangeEvent if true, the component will dispatch a "change" event if the
* value has changed. Otherwise, it will dispatch a "valueCommit" event.
*/
mx_internal function setSelectedIndex(value:int, dispatchChangeEvent:Boolean = false):void
{
if (value == selectedIndex)
return;
if (dispatchChangeEvent)
dispatchChangeAfterSelection = dispatchChangeEvent;
_proposedSelectedIndex = value;
invalidateProperties();
}
精彩评论