Open In App

SearchView in Android with RecyclerView

Improve
Improve
Like Article
Like
Save
Share
Report

Many apps represent data in the form of huge lists and for filtering these lists we have seen the SearchView present inside these apps. So for filtering this list of data we generally use a SearchView. In this article, we will take a look at the implementation of Search View in Android with a RecyclerView in Android. 

What We are Going to Build in this Article? 

We will be building a simple application in which we will display a list of data in the RecyclerView. We will be displaying the list of courses with its description and on that recycler view, we will add a SearchView which will be used to filter the data in our Recycler View. A sample video is given below to get an idea about what we are going to do in this article. We are going to implement this project using both Java and Kotlin Programming Language for Android.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?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"
    tools:context=".MainActivity">
 
    <!-- recycler view to display our data -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


Step 3: Creating a Model Class for Storing Our Data

Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and name your class as CourseModel and add the below code to it. 

Java




public class CourseModel {
    // variables for our course
    // name and description.
    private String courseName;
    private String courseDescription;
 
    // creating constructor for our variables.
    public CourseModel(String courseName, String courseDescription) {
        this.courseName = courseName;
        this.courseDescription = courseDescription;
    }
 
    // creating getter and setter methods.
    public String getCourseName() {
        return courseName;
    }
 
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
 
    public String getCourseDescription() {
        return courseDescription;
    }
 
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
}


Kotlin




class CourseModel(private var courseName: String, private var courseDescription: String) {
    // creating getter and setter methods.
    fun getCourseName(): String {
        return courseName
    }
 
    fun setCourseName(courseName: String) {
        this.courseName = courseName
    }
 
    fun getCourseDescription(): String {
        return courseDescription
    }
 
    fun setCourseDescription(courseDescription: String) {
        this.courseDescription = courseDescription
    }
}


Step 4: Creating a Layout File for Our Item of RecyclerView

Navigate to the app > res > layout > Right-click on it > New > layout resource file and name your layout as course_rv_item and add the below code to it.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <!-- text view for our course name -->
        <TextView
            android:id="@+id/idTVCourseName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="Course Name"
            android:textColor="@color/black"
            android:textSize="18sp" />
 
        <!-- text view for our course description -->
        <TextView
            android:id="@+id/idTVCourseDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCourseName"
            android:padding="5dp"
            android:text="Course Description"
            android:textColor="@color/black" />
    </RelativeLayout>
</androidx.cardview.widget.CardView>


Step 5: Creating an Adapter Class for Setting Data to Items of Our RecyclerView 

Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and name it as CourseAdapter and add the below code to it. 

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
 
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> {
 
    // creating a variable for array list and context.
    private ArrayList<CourseModel> courseModelArrayList;
 
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList<CourseModel> courseModelArrayList, Context context) {
        this.courseModelArrayList = courseModelArrayList;
    }
 
    // method for filtering our recyclerview items.
    public void filterList(ArrayList<CourseModel> filterlist) {
        // below line is to add our filtered
        // list in our course array list.
        courseModelArrayList = filterlist;
        // below line is to notify our adapter
        // as change in recycler view data.
        notifyDataSetChanged();
    }
     
    @NonNull
    @Override
    public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
 
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModel model = courseModelArrayList.get(position);
        holder.courseNameTV.setText(model.getCourseName());
        holder.courseDescTV.setText(model.getCourseDescription());
    }
 
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return courseModelArrayList.size();
    }
 
    public static class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views.
        private final TextView courseNameTV;
        private final TextView courseDescTV;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}


Kotlin




import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
 
class CourseAdapter(courseModelArrayList: ArrayList<Any>) : RecyclerView.Adapter<CourseAdapter.ViewHolder>() {
 
    // creating a variable for array list and context.
    private var courseModelArrayList: ArrayList<CourseModel>
 
    // method for filtering our recyclerview items.
    fun filterList(filterList: ArrayList<CourseModel>) {
        // below line is to add our filtered
        // list in our course array list.
        courseModelArrayList = filterList
        // below line is to notify our adapter
        // as change in recycler view data.
        notifyDataSetChanged()
    }
 
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        // below line is to inflate our layout.
        val view: View = LayoutInflater.from(parent.context).inflate(R.layout.course_rv_item, parent, false)
        return ViewHolder(view)
    }
 
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // setting data to our views of recycler view.
        val model: CourseModel = courseModelArrayList[position]
        holder.courseNameTV.setText(model.getCourseName())
        holder.courseDescTV.setText(model.getCourseDescription())
    }
 
    override fun getItemCount(): Int {
        // returning the size of array list.
        return courseModelArrayList.size
    }
 
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // creating variables for our views.
        lateinit var courseNameTV: TextView
        lateinit var courseDescTV: TextView
 
        init {
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName)
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription)
        }
    }
 
    // creating a constructor for our variables.
    init {
        this.courseModelArrayList = courseModelArrayList
    }
}


Step 6: Creating a Menu File for Our SearchView

Navigate to the app > res > Right-click on it > New > Directory and give a name to your directory as the menu. After creating a new directory we have to create a new menu file inside it. For creating a new menu file. Navigate to the app > res > menu > Right-click on it > New > menu resource file, name it as search_menu and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <!-- item for our search view with its id -->
    <item
        android:id="@+id/actionSearch"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
</menu>


Step 7: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for
    // our ui components.
    private RecyclerView courseRV;
 
    // variable for our adapter
    // class and array list
    private CourseAdapter adapter;
    private ArrayList<CourseModel> courseModelArrayList;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
 
        // calling method to
        // build recycler view.
        buildRecyclerView();
    }
 
    // calling on create option menu
    // layout to inflate our menu file.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // below line is to get our inflater
        MenuInflater inflater = getMenuInflater();
 
        // inside inflater we are inflating our menu file.
        inflater.inflate(R.menu.search_menu, menu);
 
        // below line is to get our menu item.
        MenuItem searchItem = menu.findItem(R.id.actionSearch);
 
        // getting search view of our item.
        SearchView searchView = (SearchView) searchItem.getActionView();
 
        // below line is to call set on query text listener method.
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
 
            @Override
            public boolean onQueryTextChange(String newText) {
                // inside on query text change method we are
                // calling a method to filter our recycler view.
                filter(newText);
                return false;
            }
        });
        return true;
    }
 
    private void filter(String text) {
        // creating a new array list to filter our data.
        ArrayList<CourseModel> filteredlist = new ArrayList<CourseModel>();
 
        // running a for loop to compare elements.
        for (CourseModel item : courseModelArrayList) {
            // checking if the entered string matched with any item of our recycler view.
            if (item.getCourseName().toLowerCase().contains(text.toLowerCase())) {
                // if the item is matched we are
                // adding it to our filtered list.
                filteredlist.add(item);
            }
        }
        if (filteredlist.isEmpty()) {
            // if no item is added in filtered list we are
            // displaying a toast message as no data found.
            Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
        } else {
            // at last we are passing that filtered
            // list to our adapter class.
            adapter.filterList(filteredlist);
        }
    }
 
    private void buildRecyclerView() {
 
        // below line we are creating a new array list
        courseModelArrayList = new ArrayList<CourseModel>();
 
        // below line is to add data to our array list.
        courseModelArrayList.add(new CourseModel("DSA", "DSA Self Paced Course"));
        courseModelArrayList.add(new CourseModel("JAVA", "JAVA Self Paced Course"));
        courseModelArrayList.add(new CourseModel("C++", "C++ Self Paced Course"));
        courseModelArrayList.add(new CourseModel("Python", "Python Self Paced Course"));
        courseModelArrayList.add(new CourseModel("Fork CPP", "Fork CPP Self Paced Course"));
 
        // initializing our adapter class.
        adapter = new CourseAdapter(courseModelArrayList, MainActivity.this);
 
        // adding layout manager to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
 
        // setting layout manager
        // to our recycler view.
        courseRV.setLayoutManager(manager);
 
        // setting adapter to
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}


Kotlin




import android.os.Bundle
import android.view.Menu
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.*
 
class MainActivity : AppCompatActivity() {
    // creating variables for
    // our ui components.
    private lateinit var courseRV: RecyclerView
 
    // variable for our adapter
    // class and array list
    private lateinit var adapter: CourseAdapter
    private lateinit var courseModelArrayList: ArrayList<Any>
     
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses)
 
        // calling method to
        // build recycler view.
        buildRecyclerView()
    }
 
    // calling on create option menu
    // layout to inflate our menu file.
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // below line is to get our inflater
        val inflater = menuInflater
 
        // inside inflater we are inflating our menu file.
        inflater.inflate(R.menu.search_menu, menu)
 
        // below line is to get our menu item.
        val searchItem = menu.findItem(R.id.actionSearch)
 
        // getting search view of our item.
        val searchView = searchItem.actionView
 
        // below line is to call set on query text listener method.
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                return false
            }
 
            override fun onQueryTextChange(newText: String): Boolean {
                // inside on query text change method we are
                // calling a method to filter our recycler view.
                filter(newText)
                return false
            }
        })
        return true
    }
 
    private fun filter(text: String) {
        // creating a new array list to filter our data.
        val filteredlist = ArrayList<CourseModel>()
 
        // running a for loop to compare elements.
        for (item in courseModelArrayList) {
            // checking if the entered string matched with any item of our recycler view.
            if (item.getCourseName().toLowerCase().contains(text.lowercase(Locale.getDefault()))) {
                // if the item is matched we are
                // adding it to our filtered list.
                filteredlist.add(item)
            }
        }
        if (filteredlist.isEmpty()) {
            // if no item is added in filtered list we are
            // displaying a toast message as no data found.
            Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show()
        } else {
            // at last we are passing that filtered
            // list to our adapter class.
            adapter.filterList(filteredlist)
        }
    }
 
    private fun buildRecyclerView() {
 
        // below line we are creating a new array list
        courseModelArrayList = ArrayList<CourseModel>()
 
        // below line is to add data to our array list.
        courseModelArrayList.add(CourseModel("DSA", "DSA Self Paced Course"))
        courseModelArrayList.add(CourseModel("JAVA", "JAVA Self Paced Course"))
        courseModelArrayList.add(CourseModel("C++", "C++ Self Paced Course"))
        courseModelArrayList.add(CourseModel("Python", "Python Self Paced Course"))
        courseModelArrayList.add(CourseModel("Fork CPP", "Fork CPP Self Paced Course"))
 
        // initializing our adapter class.
        adapter = CourseAdapter(courseModelArrayList, this)
 
        // adding layout manager to our recycler view.
        val manager = LinearLayoutManager(this)
        courseRV.setHasFixedSize(true)
 
        // setting layout manager
        // to our recycler view.
        courseRV.layoutManager = manager
 
        // setting adapter to
        // our recycler view.
        courseRV.adapter = adapter
    }
}


Output:



Last Updated : 17 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads