먼저 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'를 입력하면 예측 텍스트에 'eye'가 권장 될 수 있습니다. 사용자가 '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);
}