まず、EditTextとListViewの両方を含むXMLレイアウトを作成する必要があります。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Pretty hint text, and maxLines -->
<EditText android:id="@+building_list/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type to filter"
android:inputType="text"
android:maxLines="1"/>
<!-- Set height to 0, and let the weight param expand it -->
<!-- Note the use of the default ID! This lets us use a
ListActivity still! -->
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
/>
</LinearLayout>
これにより、すべてが適切にレイアウトされ、ListViewの上にEditTextが表示されます。次に、通常どおりにListActivityを作成しますがsetContentView()、onCreate()メソッドに呼び出しを追加して、最近宣言したレイアウトを使用します。でListView特別にIDを付けたことを忘れないでくださいandroid:id="@android:id/list"。これにより、宣言したレイアウトでListActivityどちらListViewを使用するかをが知ることができます。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filterable_listview);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList());
}
アプリを実行するListViewと、前のが表示され、上に素敵なボックスが表示されます。そのボックスに何かをさせるには、ボックスから入力を受け取り、その入力をリストにフィルターする必要があります。多くの人がこれを手動で実行しようとしましたが、ほとんどの ListView Adapterクラスには、Filter自動的にフィルタリングを実行するために使用できるオブジェクトが付属しています。私達はちょうどからパイプへの入力が必要EditTextにFilter。結構簡単です。簡単なテストを実行するには、この行をonCreate()呼び出しに追加します
adapter.getFilter().filter(s);
ListAdapterこれを機能させるには、変数を変数に保存する必要があることに注意してくださいArrayAdapter<String>。以前の変数を「アダプター」という変数に保存しました。
次のステップは、から入力を取得することEditTextです。これは実際には少し考えが必要です。をに追加できOnKeyListener()ますEditText。ただし、このリスナーは一部のキーイベントのみを受け取ります。たとえば、ユーザーが「wyw」と入力した場合、予測テキストは「目」を推奨する可能性があります。ユーザーが「wyw」または「eye」を選択するまで、OnKeyListenerキーイベントは受信されません。一部の人はこのソリューションを好むかもしれませんが、私はそれが苛立たしいと思いました。すべての重要なイベントが必要だったので、フィルタリングするかしないかを選択できました。解決策はTextWatcherです。単純に作成して追加TextWatcherするEditTextと、パスListAdapter Filterテキストを変更するたびに、フィルタ要求を。を削除することTextWatcherを忘れないでくださいOnDestroy()!これが最終的な解決策です:
private EditText filterText = null;
ArrayAdapter<String> 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<String>(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);
}