logo

Many times we want to filter the ListView based on what user types and in Android, simple straightforward way to filter the list in Android is as follows:
1) Create Layout XML


    
     

2) Create Activity Class
It has got EditText and ListView. We want that as user will type in

EditText the ListView should get filter. So here is our Activity class:

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);

    adapter=new ArrayAdapter(this,
                   android.R.layout.simple_list_item_1, 
                   getStringArrayList()
    setListAdapter(adapter);
}

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);
}

Here,
1) We create the adapter with default android simple_list_item_1 layout.
2) We want the list to be filtered as user will type in EditText, so, we created TextWatcher and added that as TextChangedListener in Line 11.
3) ListView Adapter classes come with a Filter object that can be used to perform the filtering automatically. We just need to pipe the input from the EditText into the Filter. You can check out on Line no. 30. Filter checks whether entered string contained in each item of String ArrayAdapter.

Output
Running the app now should show previous ListView, with a nice text box above. As user will type into that textbox, the list will get filtered.

Limitations
1) It only works with String Array adapter. If we have our own Custom array adapter then it will not work.
2) We cannot apply our own filter. Default filter filters the List in “contains” fashion. But if we want our own filter (for eg: filtering list in “starts with fashion”) we cannot do that.

Ofcourse, there is trick to overcome both this limitation :-). Please check next tutorial to check how to overcome this limitation.

AUTHOR: Mahavir Jain

Founder @CodeToArt, Leads Android Development at CodeToArt.

No Comments

Leave a Comment

Your email address will not be published.