문제

안드로이드에서 어떻게 할 수 있습니까? ListView 표시된 항목이 동적으로 업데이트되는 사용자 입력을 기반으로 필터 TextView 값?

나는 다음과 같은 것을 찾고 있습니다.

-------------------------
| Text View             |
-------------------------
| List item             |
| List item             |
| List item             |
| List item             |
|                       |
|                       |
|                       |
|                       |
-------------------------
도움이 되었습니까?

해결책

먼저 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 위의 멋진 편집 텍스트와 함께 모든 것이 올바르게 배치됩니다. 다음으로, 평소와 같이 ListActivity를 만들지 만 추가하십시오. setContentView() 전화로 전화하십시오 onCreate() 방법으로 최근에 선언 된 레이아웃을 사용합니다. 우리가 이드를 받았다는 것을 기억하십시오 ListView 특히 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 수업은 a Filter 자동으로 필터링을 수행하는 데 사용할 수있는 객체. 우리는 단지 입력을 파이프로 파이프해야합니다 EditTextFilter. 그것은 매우 쉽습니다. 빠른 테스트를 실행하려면이 라인을 추가하십시오. onCreate() 전화

adapter.getFilter().filter(s);

저장해야합니다 ListAdapter 이 작업을 수행하기위한 변수에게 - 나는 내 ArrayAdapter<String> 이전부터 '어댑터'라는 변수로.

다음 단계는 입력을 얻는 것입니다 EditText. 이것은 실제로 약간의 생각이 필요합니다. 당신은 추가 할 수 있습니다 OnKeyListener() 너의 ~에게 EditText. 그러나이 청취자는 만받습니다 몇 가지 주요 이벤트. 예를 들어, 사용자가 'WYW'에 들어가면 예측 텍스트는 '눈'을 권장 할 것입니다. 사용자가 'Wyw'또는 'Eye'를 선택할 때까지 OnKeyListener 주요 이벤트를받지 않습니다. 일부는이 솔루션을 선호 할 수도 있지만 실망 스럽습니다. 모든 키 이벤트를 원했기 때문에 필터링을 선택하거나 필터링하지 않았습니다. 해결책은 a 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);
}

다른 팁

프로그램을 실행하면 힘이 가까워집니다.

나는 라인을 교환했다 :

Android : id = "@+building_list/search_box"

~와 함께

Android : id = "@+id/search_box"

그것이 문제 일 수 있습니까? '@+building_list'는 무엇입니까?

필터링에 문제가 있었는데 결과가 필터링되었지만 복원되지 않았습니다!

필터링 (활동 시작) 전에 목록 백업을 만들었습니다 .. (동일한 데이터를 포함하는 다른 목록 만)

필터링시 필터 및리스트 타이페이터가 기본 목록에 연결되어 있습니다.

그러나 필터 자체는 백업 된 목록의 데이터를 사용했습니다.

이것은 내 경우에 목록이 즉시 업데이트되었으며 심지어 검색어 문자를 삭제할 때 심지어 모든 경우에 목록이 성공적으로 복원됩니다 :)

어쨌든이 솔루션에 감사드립니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top