Working with Android Filterable ListView | Hello, Developers! In this tutorial, we will learn how to implement a Filterable ListView. we all have worked with ListView before and we also have tutorials about ListView and Expandable ListView both. You may check them out if you want. In this project we will implement a Listview with an EditText, When we write any sequence of characters in the EditText, according to that text the Listview will be filtered in real time! We have also done some similar implementation for Spinner before. you can check that out from here

This is very important and useful implementation of ListView as when the user has a wide variety of List items to choose from, at that time this logic helps the user save time. We will make this project in 5 simple steps.

Output: –

Download Project – [media-downloader media_id=”1862″]

Download APK – [media-downloader media_id=”1866″]

Wants to Learn Advanced Android Application development from scratch- Beyond Basics


Creating New Project  –

Step 1: – Creating Project

Open your Android Studio -> Create a new project -> Choose BlankActivity > Finish

Step 2: Creating Layout for our App

activity.main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:background="#00B6FF"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <EditText android:id="@+id/inputSearch"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="Input text here.."
                android:inputType="textVisiblePassword"/>

            <ListView
                android:id="@+id/list_view"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </FrameLayout>
</LinearLayout>

We require an EditText where the user can enter the input and Listview will be filtered accordingly.

Related:

Circular Imageview in Custom Listview in Android

Android Expandable ListView Implementation

Android Custom ListView using BaseAdapter

ItemDecoration in RecyclerView in Android

How to set Adapter to Spinner Dynamically

Step 3: Customizing Appearance for each item of ListView

items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/reasturants"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="16dp"
        android:textStyle="bold" />
</LinearLayout>

The TextView defined in this layout have certain attributes and this will be the appearance of each ListView item which will be a text. An ArrayAdapter will be required to bind this layout to the Listview.

Step 4: Creating MainActivity.java

First, we require String array which will contain all item names that will be our ListView items.

String helplines_number[] = {
                "Papa Johns",
                "Dominoes",
                "Mc donalds",
                "Barbeque Nation",
                "Subway",
                "Pizza Hut",
                "Yo China!",
                "TGIF",
                "Barista",
        };

Also, we require an ArrayAdapter object to bind the list of Strings and the ListView item’s layout (i.e items.xml) to the Listview.

  adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.items, R.id.reasturants, helplines_number);
  list_view.setAdapter(adapter);

When the user clicks the ListView item, the name of the item will be displayed in Toast, the code will work whether the List has been filtered by user’s input or not. For that we use setOnItemClickListener

 list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String n = (String) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), "You Selected : " + n, Toast.LENGTH_SHORT).show();
            }
        });

After everything has been done we need to implement the Filter functionality in our ListView for which we will apply addTextChangedListener()

  • addTextChangedListener() will add a TextWatcher to the list of those whose methods are called whenever the text changes.
 inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                MainActivity.this.adapter.getFilter().filter(cs);
            }
  • The getFilter() will create a new ArrayAdapter and will help to filter the list.
  • The filter(cs) will filter the list based on the char sequence given by the user.
  • After the List is filtered or upon completion, the listener is notified.

You entire MainActivity.java will look like this:

package com.mytrendin.filterablelv;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String helplines_number[] = {
                "Papa Johns",
                "Dominoes",
                "Mc donalds",
                "Barbeque Nation",
                "Subway",
                "Pizza Hut",
                "Yo China!",
                "TGIF",
                "Barista",
        };
        ListView list_view = (ListView) findViewById(R.id.list_view);
        EditText inputSearch = (EditText) findViewById(R.id.inputSearch);


        //    Adding items to Listview
        adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.items, R.id.reasturants, helplines_number);
        list_view.setAdapter(adapter);

        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String n = (String) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), "You Selected : " + n, Toast.LENGTH_SHORT).show();

            }
        });


        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                MainActivity.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });
    }
}

Step 5: Run the Project and see the changes 

Conclusion

In this Tutorial, we learned how to implement a Filterable ListView. It is very easy and very useful implementation that all developers should be aware of. In the case of any queries you can comment below in the comment section and also you can recommend me any topic you want my next blog to be all about. Thank you for reading guys. you can download my Project and APK files from the link above. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts