package com.beyondsoft
{
import flash.events.Event;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.ComboBox;
import mx.events.FlexEvent;
import mx.utils.StringUtil;
/**
* ComboBox过滤自动完成组件
* @author 韩敬诺
*
*/
public class AutoCompleteComboBox extends ComboBox
{
public function AutoCompleteComboBox()
{
if(!width){
//如果没有指定width则设置默认的宽度
width=120;
}
setStyle("paddingLeft","0");
selectedIndex=-1;
editable=true;
addEventListener("creationComplete",init);
}
private var ac:ArrayCollection;//保存数据源
/**
*
* @param event
*
*/
private function init(event:Event):void{
ac=dataProvider as ArrayCollection;
}
/**
* 重写下三角按钮的点击事件
* @param event
*
*/
override protected function downArrowButton_buttonDownHandler(event:FlexEvent):void{
dataProvider=ac;
super.downArrowButton_buttonDownHandler(event);
}
/**
* 当输入框中的值发生变化时开始过滤
* @param event
*
*/
override protected function textInput_changeHandler(event:Event):void{
super.textInput_changeHandler(event);
//当数据源不为空并且关键字不为空时开始搜索数据源
if(ac){
var keyWord:String=StringUtil.trim(textInput.text);
if(keyWord){
searchKeyWord(keyWord);
}
}
}
/**
*
* @param keyWord关键字
*
*/
private function searchKeyWord(keyWord:String):void{
var dp:ArrayCollection=filterData(ac);
//当数据源改变的时候
if(dp.length>0){
dataProvider=dp;
dropdown.selectedIndex=-1;
dropdown.verticalScrollPosition=0;
textInput.setFocus();
//注意先设置关键字被选中后打开下拉列表
textInput.setSelection(keyWord.length,keyWord.length);
open();
}else{
dataProvider=ac;
textInput.text="";
selectedIndex=-1;
close();
}
}
/**
*
* @param item
* @return
*
*/
private function filterData(ac:ArrayCollection):ArrayCollection{
var dp:ArrayCollection=new ArrayCollection();
for(var i:int=0;i<ac.length;i++){
var item:Object=ac.getItemAt(i);
if(item.hasOwnProperty(labelField)){
var value:String=item[labelField];
if(value.indexOf(textInput.text)!=-1){
dp.addItem(item);
}
}
}
return dp;
}
}
}
网上虽然有很多例子,但是写的都有很多bug,因此自己动手写了个组件。出现了一个难点就是如何点击下三角的时候数据源全部出来,看了ComboBox后才知道是这个方法downArrowButton_buttonDownHandler,因此重写这个方法就ok了。
思路:1监听textInput_changeHandler事件
2 对数据源进行过滤
3 重写下三角的点击事件