Android RecyclerView → Android Simple RecyclerView Search/Filter – Camposha

Android RecyclerView

Android RecyclerView

Android RecyclerView

Android Simple RecyclerView Search/Filter


Searching and Filtering is an important task in programming as whole. It provides you a way to get what you want quickly without having to scroll through dozens,hundreds or thousands of items.

This is especially important in mobile devices which really do have a limited viewport. The mobile screen probably display only around 10 items per viewport. The other option is to make users scroll or to provide a search/filter facility.

Importance of Searching/Filtering for RecyclerView

No. Importance Description
1. User Experience RecyclerViews are meant to display a large data set so searching/filtering mechanisms provide better user experience.
2. Efficiency When an activity/fragment is being rendered, it’s very efficient to display just a limited amount of RecyclerView items instead of pre-fetching everything at a go.This is because adapterviews normally have to go through an expensive process of inflating of layouts especially for generic views like recyclerview.


Let’s go.

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File –> New Project.
  2. Type the application name and choose the company name.
    New Project Dialog
  3. Choose minimum SDK.
    Choose minimum SDK
  4. Choose Basic activity.
    Choose Empty Activity
  5. Click Finish.

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

        <activity android_name=".MainActivity">


                <action android_name="android.intent.action.MAIN" />

                <category android_name="android.intent.category.LAUNCHER" />



You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Advantage of Creating Basic Activity project

You can optionally choose empty activity over basic activity for this project.

However basic activity has the following advantages:

No. Advantage
1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
2. Provides us with appbar layout which implements material design appbar concepts.
3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
4. Decouples our custom content views and widgets from the templating features like toolbar.

Generated Project Structure

AndroidStudio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the file. file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

2. Dependencies

There are no special dependencies. We only need support libraries.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''
    compile ''
    compile ''

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

######### Advantages of Using XML over Java

No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It’s easily maintanable as the user interface is decoupled from your Java logic.
3. It’s easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed”

No. View/ViewGroup Package Role
1. CordinatorLayout Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
2. AppBarLayout A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar < A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton An circular imageview floating above the UI that we can use as buttons.
<?xml version="1.0" encoding="utf-8"?>


            app_popupTheme="@style/AppTheme.PopupOverlay" />


    <include layout="@layout/content_main" />

        android_src="@android:drawable/ic_dialog_email" />

(b). content_main.xml

This layout gets included in your activity_main.xml.
You define your UI widgets right here.

In this case we use a SearchView and a RecyclerView so lets add them:

<?xml version="1.0" encoding="utf-8"?>



        class="" />


3. model.xml

This is the recyclerview view items layout model. In other words the custom layout from which our recyclerview rows will be inflated.

In this case our RecyclerView items will comprise cardviews.

Our RecyclerView CardViews will comprise images and texts:

<?xml version="1.0" encoding="utf-8"?>
    android_orientation="horizontal" android_layout_width="match_parent"



            android_src="@drawable/herera" />

            android_layout_toRightOf="@+id/playerImage" />

            android_layout_alignParentRight="true" />


4. Java Classes

Let’s proceed on now and write some java code.

(a). Interface

This is an interface to define for us a simple method signature that will be implemented to handle itemclicks.

package com.tutorials.hp.simplerecyclerfilter;

import android.view.View;

public interface ItemClickListener {

    void onItemClick(View v,int pos);
(b). class

This class in our RecyclerView.ViewHolder class.

It derives from thus forcing us to create a constructor public MyHolder(View itemView) that takes a View object as a parameter and pass it over the base clas by a call to super(itemView).

Here are the roles of this class No. Role
1. Hold a View object already inflated from XML layout for recycling. This avoids re-inflation of the same layout which is an expensive process. Thus this improves the performance of list items rendering for recyclerview. The inflated View is received via the constructor
2. Searches for individual widgets by their id from the inflated View and defines instance fields them. This ensures that those widgets can easily be retrieved as instance fields and their values set especially inside our RecyclerView.Adapter sub-class.
3. Can also be used implement onClick event listener which can be handled by other classes especially the adapter class.
package com.tutorials.hp.simplerecyclerfilter;

import android.view.View;
import android.widget.TextView;

public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView nameTxt;
    ItemClickListener itemClickListener;

    public MyHolder(View itemView) {

        nameTxt= (TextView) itemView.findViewById(;

    public void onClick(View v) {

    public void setItemClickListener(ItemClickListener ic)

This is our RecyclerView.Adapter class.

It derives from<RecyclerView.ViewHolder myHolder> class.

Deriving from Recylcerview.Adapter will force us to either make our adapter class abstract or go ahead and override a couple of methods. We choose the latter, overriding onCreateViewHolder(ViewGroup parent, int viewType) and onBindViewHolder(MyHolder holder, final int position).

This class will adapt our data set to our RecyclerView which we use an adapterview adapterview.

Here are the main responsibilities of this class:

No. Responsibility
1. This class will be responsible for inflating our custom model layout to a View object to be used as our RecyclerView itemView.
2. A RecyclerView.ViewHolder instance will then be created with the View object passed to it. All these we do inside the onCreateVewHolder() method.
3. We’ll then bind data to our view widgets inside the onBindViewHolder().
4. Handling of click events for our inflated View item.
5. Returning the total item Count to be used when rendering our view items.

Furthermore we really need to make our recyclerview adapter searchable.

So we need to implement the android.widget.Filter.Filterable interface:

public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable{}

We’ll then create an inner class inside the class and make it derive from android.widget.Filter class:

    class CustomFilter extends Filter {}

We then override two methods to help us in filtering searching.

In the first we performs filtering:

        protected FilterResults performFiltering(CharSequence constraint) {...}

while in the second we publish a result:

        protected void publishResults(CharSequence constraint, FilterResults results) {..}

Here’s the code:

Our Activity


This is our MainActivity.

Here are the roles it performs for us:

No. Role
1. It is our Activity class hence is responsible for rendering our Views. In this case our SearchView and RecyclerView.
2. It defines an array that acts as our data source.
3. It references our Views : SearchView and RecyclerView from our xml layout specifications.
4. It instantiates our MyAdapter class and sets it to our RecyclerView.
5. It sets queryTextListener to our searchview and listens to text change events, therefore invoking the getFilter() of our MyAdapter class.

Leave a Reply

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

Join Us