Add Search filter on Recycler View with CardView layout

In android development, this is about implementing the search filter with Edittext widget on RecyclerView  having CardView layout. We will use EditText widget to get string given by user and will search the input string in list to show the filtered result.
With material design style, the theme can be combined in an Activity.

Adding Support libraries in the dependencies

For making list of items, we need to add the RecyclerView and CardView support library and design support library  to use Material Design Widgets in gradle dependencies (at app level gradle file).

app/build.gradle
  1. apply plugin: 'com.android.application'

  2. android {
  3.     compileSdkVersion 24
  4.     buildToolsVersion "25.0.0"
  5.     defaultConfig {
  6.         applicationId "test.codedivas.com.searchonrecyclerview"
  7.         minSdkVersion 14
  8.         targetSdkVersion 24
  9.         versionCode 1
  10.         versionName "1.0"
  11.         
  12. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  13.     }
  14.     buildTypes {
  15.         release {
  16.             minifyEnabled false
  17.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  18.         }
  19.     }
  20. }

  21. dependencies {
  22.     compile fileTree(dir: 'libs', include: ['*.jar'])
  23.     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  24.         exclude group: 'com.android.support', module: 'support-annotations'
  25.     })
  26.     compile 'com.android.support:appcompat-v7:24.2.1'
  27.     compile 'com.android.support:design:24.2.1'
  28.     compile 'com.android.support:recyclerview-v7:24.2.0'
  29.     compile 'com.android.support:cardview-v7:24.2.0'
  30.     testCompile 'junit:junit:4.12'

  31. }

Designing Activity Layout

Here we will use EditText to put the string to be searched and RecyclerView to display the list of items. 
The layout should be like:

activity_main.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent"
  6.     xmlns:app="http://schemas.android.com/apk/res-auto">

  7.             <EditText
  8.                 android:id="@+id/search"
  9.                 android:layout_gravity="center_vertical"
  10.                 android:layout_width="match_parent"
  11.                 android:layout_height="wrap_content"
  12.                 android:padding_left="20dp"
  13.                 android:padding_right="20dp"
  14.                 android:layout_marginTop="2dp"
  15.                 android:textSize="16sp"
  16.                 android:hint="Search Here" 
  17.                                                            />

  18.         <android.support.v4.widget.RecyclerView
  19.             android:id="@+id/recyclerview"
  20.             android:layout_width="match_content"
  21.             android:layout_height="match_parent"
  22.             android:layout_marginTop="2dp"
  23.             android:drawSelectorOnTop="true"
  24.             android:background="#D0D0D0"
  25.             app:layout_scrollFlags="scroll| enterAlways"
  26.             app:layout_behavior="@string/appbar_scrolling_view_behavior" />

  27. </LinearLayout>
Here, Create a list_item.xml file to display the list of items. The layout of the list item should be like this:

list_item.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"

  5. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  6.     android:layout_width="wrap_parent"
  7.     android:layout_height="wrap_parent"

  8. <android.support.v7.widget.CardView
  9.     xmlns:android="http://schemas.android.com/apk/res/android"
  10.     xmlns:card_view="http://schemas.android.com/apk/res-auto"
  11.     android:id="@+id/cvItem"
  12.     android:layout_gravity="top"
  13.     android:layout_width="match_parent"
  14.     android:layout_height="65dp"
  15.     android:layout_marginBottom="4dp"
  16.     android:layout_marginLeft="8dp"
  17.     android:layout_marginRight="8dp"
  18.     android:layout_marginTop="4dp"
  19.     android:minHeight="65dp"
  20.     card_view:cardCornerRadius="10dp">

  21.     <LinearLayout
  22.         xmlns:android="http://schemas.android.com/apk/res/android"
  23.         android:id="@+id/text_container"
  24.         android:layout_width="match_parent"
  25.         android:layout_height="65dp"
  26.         android:minHeight="65dp"
  27.         android:gravity="center_vertical"
  28.         android:orientation="vertical">

  29.         <TextView
  30.             android:id="@+id/country_name"
  31.             android:paddingLeft="16dp"
  32.             android:textSize="16sp"
  33.             android:layout_width="match_parent"
  34.             android:layout_height="wrap_content"
  35.             android:textAppearance="?android:textAppearanceSmall"
  36.             android:textColor="@android:color/black"
  37.             android:alignParentTop="true" />

  38.     </LinearLayout>

  39. </android.support.v7.widget.CardView>
  40.     </RelativeLayout>
  41.     </RelativeLayout>

Program Code

In Main Activity, initialize ids of all the views and create an ArrayList to populate data in the list. Here, fruitList( ) method is created. In this method, the list of fruits is added in the ArrayList.

Source code should be like:

MainActivity.java

  1. package test.codedivas.com.searchonrecyclerview;

  2. import android.widget.EditText;
  3. import android.os.Bundle;
  4. import android.support.v7.widget.RecyclerView;
  5. import android.support.v7.widget.LinearLayoutManager;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.support.v7.widget.Toolbar;
  8. import android.text.TextWatcher;
  9. import android.text.Editable;
  10. import java.util.List;
  11. import java.util.ArrayList;

  12. public class MainActivity extends AppCompatActivity {  

  13.     private RecyclerView mRecyclerview;
  14.     public EditText search;
  15.     private List list = new ArrayList();
  16.     public SimpleAdapter mAdapter;

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

  21.         search= (EditText)findViewById(R.id.search);

  22.         mRecyclerView= (RecyclerView) findViewById(R.id.recyclerview);

  23.         mRecyclerView.setLayoutManager(new LinearLayoutManager(this));// to manage the positions of the items in recyclerview 
  24.         mRecyclerView.setHasFixedSize(true);
  25.          fruitList();

  26.         mAdapter = new SimpleAdapter(list, this);
  27.         mRecyclerView.setAdapter(mAdapter);

  28.         addTextListener();//it is made below to add search operation
  29.        }

  30.         //this method is used to create items
  31.     public void fruitList(){

  32.         list.add("Pomegranate");
  33.         list.add("Apple");
  34.         list.add("Pear");
  35.         list.add("Mango");
  36.         list.add("Banana");
  37.         list.add("Watermelon");
  38.         list.add("Strawberry");
  39.         list.add("Orange");
  40.         list.add("Guava");
  41.         list.add("Kiwi");
  42.         list.add("Lichi");
  43.         list.add("Grapes");
  44.         list.add("Cherry");
  45.         list.add("Melon");
  46.         list.add("Blue Berries");
  47.         list.add("Wood Apple");
  48.       }

  49.         //implementing search operation 
  50.  public void addTextListener(){

  51. search.addTextChangedListener(new TextWatcher(){

  52.    public void afterTextChanged ( Editable s){  }

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

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

  55.       query = query.toString().toLowerCase();
  56.             
  57.             final List<String> filteredList = new ArrayList<>();

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

  59.             final String text = list.get(i).toLowerCase();
  60.             if(text.contains(query)){  filteredList.add(list.get(i)); 
  61.              }
  62.                      }

  63.    mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this)); 
  64.         mRecyclerView.setAdpater(mAdapter);

  65.         mAdapter = new SimpleAdapter(filteredList, MainActivity.this);
  66.         mAdapter .notifyDataSetChanged();// data set changed

  67.                      } 
  68.               });
  69.        }
  70. }

Creating an Adapter Class

This adapter class has special features to add custom  ViewHolder class to improve the performance of RecyclerView class.The adapter class is given as below:

SimpleAdapter.java
  1. package test.codedivas.com.searchonrecyclerview;

  2. import android.content.Context
  3. import android.support.v7.widget.CardView;
  4. import android.support.v7.widget.RecyclerView;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.TextView;
  9. import android.widget.Toast;
  10. import java.widget.List;

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

  12.    private List<String> list_item;
  13.    public Context mcontext;   

  14.      public SimpleAdapter(List<String> list, Context context) {
  15.         list_item =  list;
  16.         mcontext =  context;
  17.     }

  18.     @Override
  19.     public SimpleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)  {
  20.         //create a layout
  21.         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, null);

  22.            MyViewHolder myViewHolder = new MyViewHolder(view);
  23.             return myViewHolder;
  24.         }

  25.    @Override
  26.     public void onBindViewHolder(final MyViewHolder viewHolder, int position) {
  27.         viewHolder.country_name.setText(list_item.get(position));
  28.        viewHolder.country_name.setOnClickListener( new View.OnClickListener(){

  29.      @Override
  30.        public void onClick(View v) { 
  31.  Toast.makeText(mcontext, list_item.get(position), Toast.LENGTH_LONG).show();
  32.          }
  33.      });
  34.   } 

  35.     //initializes textview in the class
  36.   public static class MyViewHolder extends RecyclerView.ViewHolder {
  37.         public CardView cardView;
  38.         public TextView country_name;
  39.        View textContainer;

  40.         public MyViewHolder(View itemLayoutView) {

  41.             super(itemLayoutView);
  42.         
  43.             cardView = (CardView)itemLayoutView.findViewById(R.id.cvItem);
  44.             country_name = (TextView) itemLayoutView.findViewById(R.id.country_name );
  45.             textContainer = itemLayoutView.findViewById(R.id.text_container);
  46.               }
  47.         }

  48.     @Override
  49.     public int getItemCount() {
  50.         return list_item.size();
  51.     }
  52. }
    The manifest file should be like this:

    AndroidManifest.xml
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3.     package="test.codedivas.com.searchonrecyclerview">

    4.     <application
    5.         android:allowBackup="true"
    6.         android:icon="@mipmap/ic_launcher"
    7.         android:label="@string/app_name"
    8.         android:supportsRtl="true"
    9.         android:theme="@style/AppTheme">
    10.         <activity
    11.             android:name=".MainActivity"
    12.             android:label="@string/app_name"
    13.             android:theme="@style/AppTheme">
    14.             <intent-filter>
    15.                 <action android:name="android.intent.action.MAIN" />
    16.                 <category android:name="android.intent.category.LAUNCHER" />
    17.             </intent-filter>
    18.           </activity>
    19.     </application>

    20. </manifest>

    Running Application

    Demo Video :


    Output should be like: 



    Searching a string in list:




    Toast message after clicking the RecyclerView's list item:






    Conclusions

    Through this post, I hope you could learn about  implementing search operation on the popular and powerful widgets in developing Android Application. Further, you can subscribe my blog  to get the newest tutorials..!

    Enjoy Coding! :)

    1 comment:

    1. CASINO GAMING DOWNSIDE - MapyRO
      Casinos 서산 출장마사지 in Miami Beach, FL can 여주 출장마사지 be found 부천 출장마사지 by 계룡 출장마사지 simply following the search results and heading to the 밀양 출장마사지 main page of this website.

      ReplyDelete

    Add Search filter on Recycler View with CardView layout

    In android development, this is about implementing the search filter with Edittext widget on  RecyclerView    having  CardView  layout. ...

    Popular Posts