Android Search to RecyclerView Tutorial

In this tutorial, you will learn how to implement Search functionality in RecyclerView in an Android Application.

 
 

Introduction

RecyclerView is the more advanced version of ListView with large data set that can be scrolled.

In this tutorial, we will implement search functionality in RecyclerView. We will use the EditText widget to get the string by user and will search input string in the list to show the filter result. We will use RecyclerView to make the list view




Adding Support Library in the dependencies

To make the list of items, we need to add recyclerview support library in the dependencies. Open build.gradle(app module) and add library in the dependencies. Use the following code to add the library.

dependencies {
   ....
    compile 'com.android.support:recyclerview-v7:23.1.1'
   ....
}

 

Creating layout

We have to add RecyclerView to display the list of items and a EditText to input the string or keyword we need to search in the list. So, we will add the RecyclerView and EditText in the activity_main.xml file.

<<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="app.searchinrecyclerview.MainActivity">


    <EditText
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:textSize="16sp"
        android:hint="Search here"
        android:layout_marginTop="20dp" />

    <View
        android:id="@+id/border"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_below="@+id/search"
        android:layout_marginTop="14dp"
        android:background="#d3d3d3"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/border"/>

</RelativeLayout>

 

Create a new list_item.xml to show the list of items. Add the following code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.numetriclabz.androidsearch.MainActivity">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/country_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:textColor="#0b0080"
            android:textSize="16dp" />

    </RelativeLayout>

</RelativeLayout>

 

Initialize the Id of EditText and RecyclerView

To use the properties of EditText and RecyclerView, we initialize the id of EditText and RecyclerView.

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public EditText search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = (EditText) findViewById( R.id.search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    }
}

 

To improve the performance of RecyclerView, add the following code:

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public EditText search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = (EditText) findViewById( R.id.search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
    }
}

 

Set the Layout Manager

Add the LayoutManager to manage the position of its items in the RecyclerView.

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public EditText search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = (EditText) findViewById( R.id.search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

 

Creating an ArrayList

Create an ArrayList to populate the data in the list. We will create a countryList() method. In this method, we will add the list of item in the array list.

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public EditText search;
    private List<String> list = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = (EditText) findViewById( R.id.search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        countryList();  // in this method, Create a list of items.
    }

    // this method is used to create list of items.
    public void countryList(){

        list.add("Afghanistan");
        list.add("Albania");
        list.add("Algeria");
        list.add("Bangladesh");
        list.add("Belarus");
        list.add("Canada");
        list.add("Cape Verde");
        list.add("Central African Republic");
        list.add("Denmark");
        list.add("Dominican Republic");
        list.add("Egypt");
        list.add("France");
        list.add("Germany");
        list.add("Hong Kong");
        list.add("India");
        list.add("Iceland");
    }
}

 

Creating an Adapter class

The RecyclerView.Adapter class is similar to Adapter class of listview and this class has a special feature to add custom ViewHolder class to improve performance of RecyclerView class. To Learn how to implement Adapter class go to Android RecyclerView with animation tutorial. Final Adapter class is given below:

 

public class SimpleAdapter extends
        RecyclerView.Adapter<SimpleAdapter.MyViewHolder> {

    private List<String> list_item ;
    public Context mcontext;



    public SimpleAdapter(List<String> list, Context context) {

        list_item = list;
        mcontext = context;
    }

    // Called when RecyclerView needs a new RecyclerView.ViewHolder of the given type to represent an item.
    @Override
    public SimpleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                           int viewType) {
        // create a layout
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list_item, null);

        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    // Called by RecyclerView to display the data at the specified position.
    @Override
    public void onBindViewHolder(final MyViewHolder viewHolder, final int position ) {


        viewHolder.country_name.setText(list_item.get(position));

        viewHolder.country_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(mcontext, list_item.get(position),
                        Toast.LENGTH_LONG).show();
            }
        });

    }

    // initializes textview in this class
    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView country_name;

        public MyViewHolder(View itemLayoutView) {
            super(itemLayoutView);

            country_name = (TextView) itemLayoutView.findViewById(R.id.country_name);

        }
    }

    //Returns the total number of items in the data set hold by the adapter.
    @Override
    public int getItemCount() {
        return list_item.size();
    }

}

 

Set the Adapter

Set the adapter by using setAdapter() method in the MainActivity.java file.

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public EditText search;
    private List<String> list = new ArrayList<String>();
    public SimpleAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        search = (EditText) findViewById( R.id.search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        countryList();  // in this method, Create a list of items.

        // call the adapter with argument list of items and context.
        mAdapter = new SimpleAdapter(list,this);
        mRecyclerView.setAdapter(mAdapter);
        
    }

    // this method is used to create list of items.
    public void countryList(){

        list.add("Afghanistan");
        list.add("Albania");
        list.add("Algeria");
        list.add("Bangladesh");
        list.add("Belarus");
        list.add("Canada");
        list.add("Cape Verde");
        list.add("Central African Republic");
        list.add("Denmark");
        list.add("Dominican Republic");
        list.add("Egypt");
        list.add("France");
        list.add("Germany");
        list.add("Hong Kong");
        list.add("India");
        list.add("Iceland");
    }
}

 

Adding Search Functionality

We will create addTextListener() method to set the EditText Listener method. This Listener method will search in the list for a matching string, which is provided by user. Call the notifyDataSetChanged() method to change the data set in the RecyclerView.

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public EditText search;
    private List<String> list = new ArrayList<String>();
    public SimpleAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        search = (EditText) findViewById( R.id.search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        countryList();  // in this method, Create a list of items.

        // call the adapter with argument list of items and context.
        mAdapter = new SimpleAdapter(list,this);
        mRecyclerView.setAdapter(mAdapter);

        addTextListener();
    }

    // this method is used to create list of items.
    public void countryList(){

        list.add("Afghanistan");
        list.add("Albania");
        list.add("Algeria");
        list.add("Bangladesh");
        list.add("Belarus");
        list.add("Canada");
        list.add("Cape Verde");
        list.add("Central African Republic");
        list.add("Denmark");
        list.add("Dominican Republic");
        list.add("Egypt");
        list.add("France");
        list.add("Germany");
        list.add("Hong Kong");
        list.add("India");
        list.add("Iceland");
    }

     public void addTextListener(){

        search.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence query, int start, int before, int count) {

                 query = query.toString().toLowerCase();

                final List<String> filteredList = new ArrayList<>();

                for (int i = 0; i < list.size(); i++) {

                    final String text = list.get(i).toLowerCase();
                    if (text.contains(query)) {

                        filteredList.add(list.get(i));
                    }
                }

                mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                mAdapter = new SimpleAdapter(filteredList, MainActivity.this);
                mRecyclerView.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();  // data set changed
            }
        });
    }
}

 

search in recyclerview
 

search to recyclerview
 

 



The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com
  • Rajesh tiwari

    Thanks to provide, it solved my problem

  • Sachin

    hey abhay , can you make one tutorial where each row of the recyler view has a textview and a button , on clicking of this button i will increaset the value of the text view , i am doing this But after scrolling the value of thext view again setting to the 1 default value

    pls make this bro

    • Hi Sachin,

      Can you Share your code? I will help you.

  • Rohit Bansal

    Thanks to provide, it solved my problem. i really thankful of you

    • abhayanand1910

      Welcome rohit, Glad it helped you.

  • Sommy

    solved my issue, thanks bro

    • abhayanand1910

      Glad it helped you

  • Sagar Aghara

    Thank you Sir..for this tutorials…..but sir in my Project your above code is worked….but i have one more Action in RecycleView……when i search in EditText it properly worked….but after Searching when i click on any Country click event not worked…why sir…?

    • Sagar Aghara

      i had Open an another activity on click event…but it not worked…after EditText Searching……but Before Searching Click event working properly…

      • abhayanand1910

        We missed some thing, please review your code, Can you comment your code ?

        • Sagar Aghara

          Thanks for replay….Yes sir i put my Code.

          Sir….my problem is After Searching on Edit Text…..Intent Click event is not working…..
          but before searching intent of Second Activity working properly…Tnx in Advance.

        • Sagar Aghara

          Sir i Uploaded my code….where is gone….???