首先,您需要建立一個包含EditText和ListView的XML布局。
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type to filter"
android:inputType="text"
android:maxLines="1"/>
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
/>
這将使一切正常,在ListView上方有一個很好的EditText。接下來,像往常一樣建立ListActivity,但在onCreate()方法中添加setContentView()調用,以便我們使用最近聲明的布局。請記住,我們特别使用android:id="@android:id/list"來識别ListView。這允許ListActivity知道我們想要在我們聲明的布局中使用哪個ListView。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filterable_listview);
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
getStringArrayList());
}現在運作應用程式應該顯示您之前的ListView,上面有一個很好的框。為了使該框執行某些操作,我們需要從中擷取輸入,并使該輸入過濾清單。雖然很多人嘗試手動執行此操作,但大多數ListView Adapter類附帶了一個Filter對象,可用于自動執行過濾。我們隻需要将EditText的輸入傳輸到Filter。事實證明這很容易。要運作快速測試,請将此行添加到您的onCreate()電話中
adapter.getFilter().filter(s);請注意,您需要将ListAdapter儲存到變量才能使其正常工作 - 我已将之前的ArrayAdapter儲存到名為“adapter”的變量中。
下一步是從EditText擷取輸入。這實際上需要一些思考。您可以将OnKeyListener()添加到您的EditText。但是,此偵聽器僅接收一些關鍵事件。例如,如果使用者輸入“wyw”,預測文本可能會推薦“眼睛”。在使用者選擇“wyw”或“eye”之前,您的OnKeyListener将不會收到關鍵事件。有些人可能更喜歡這種解決方案,但我發現它令人沮喪。我想要每個關鍵事件,是以我可以選擇過濾或不過濾。解決方案是TextWatcher。隻需建立并将TextWatcher添加到EditText,并在每次文本更改時将ListAdapter Filter傳遞給過濾器請求。請記得删除OnDestroy()中的TextWatcher!這是最終的解決方案:
private EditText filterText = null;
ArrayAdapter adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filterable_listview);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
getStringArrayList());
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
@Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}