How to create filter for ListView items in Android.

Published by Igor Khrupin on

Please. have a look at screenshot.

Here I want to show you how to create filter for ListView items. In this post my ListView contains simple strings.
As you see there the EditText on the screen. User can type text in this EditText and ListView will filter using user’s text in EditText.

This code works very fast.

Please have a look source code:

package com.hrupin.sample.filterlist;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class FilterListSampleActivity extends Activity implements TextWatcher {
    
    private static List<String> countries = Storage.getCountries();
    private EditText editTextFilter;
    private ListView listViewCountries;
    private ArrayAdapter<String> adapter;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
        
        editTextFilter = (EditText)findViewById(R.id.editTextFilter);
        editTextFilter.addTextChangedListener(this);
        
        listViewCountries = (ListView)findViewById(R.id.listViewCountries);
        listViewCountries.setAdapter(adapter);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        adapter.getFilter().filter(s);
    }

    @Override
    public void afterTextChanged(Editable s) {}
    
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

}

All functionality goes around TextChangedListener which added in EditText.

In the next post (How to create filter for ListView items in Android. Part-2. List with custom adapter.) I’ll show you how to create filter for ListView with custom adapter and complex objects in it.

That’s all.
Here you can download the source code of sample Android project

Download it from github

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.