Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
SearchView in Android with RecyclerView
Next article icon

SearchView in Android with RecyclerView

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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 are We 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.

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.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <androidx.appcompat.widget.Toolbar         android:id="@+id/toolbar"         android:layout_width="match_parent"         android:layout_height="?attr/actionBarSize"         android:background="?attr/colorPrimary"         app:popupTheme="@style/ThemeOverlay.AppCompat.Light"         app:layout_constraintTop_toTopOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintEnd_toEndOf="parent"/>       <!-- recycler view to display our data -->     <androidx.recyclerview.widget.RecyclerView         android:layout_below="@id/toolbar"         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.

CourseModel File: 

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.

course_rv_item.xml:

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     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.

CourseAdapter File: 

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. 

search_menu.xml:

XML
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     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.

MainActivity File:

Java
package com.geeksforgeeks.searchview_android;  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.Toolbar; import androidx.appcompat.widget.SearchView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView;  import java.util.ArrayList;  public class MainActivity extends AppCompatActivity {      // creating variables for UI components     private RecyclerView courseRV;     private Toolbar toolbar;      // 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 variables         courseRV = findViewById(R.id.idRVCourses);         toolbar = findViewById(R.id.toolbar);          // setting the toolbar as the ActionBar         setSupportActionBar(toolbar);          // calling method to build recycler view         buildRecyclerView();     }      // calling onCreateOptionsMenu to inflate our menu file     @Override     public boolean onCreateOptionsMenu(Menu menu) {         // get the MenuInflater         MenuInflater inflater = getMenuInflater();          // inflate the menu         inflater.inflate(R.menu.search, menu);          // get the search menu item         MenuItem searchItem = menu.findItem(R.id.actionSearch);          // get the SearchView from the menu item         SearchView searchView = (SearchView) searchItem.getActionView();          // set the on query text listener for the SearchView         searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {             @Override             public boolean onQueryTextSubmit(String query) {                 return false;             }              @Override             public boolean onQueryTextChange(String newText) {                 // call a method to filter your RecyclerView                 filter(newText);                 return false;             }         });         return true;     }      // method to filter data based on query     private void filter(String text) {         // creating a new array list to filter data         ArrayList<CourseModel> filteredlist = new ArrayList<>();          // running a for loop to compare elements         for (CourseModel item : courseModelArrayList) {             // checking if the entered string matches any item of our recycler view             if (item.getCourseName().toLowerCase().contains(text.toLowerCase())) {                 // adding matched item to the filtered list                 filteredlist.add(item);             }         }          if (filteredlist.isEmpty()) {             // displaying a toast message if no data found             Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();         } else {             // passing the filtered list to the adapter class             adapter.filterList(filteredlist);         }     }      // method to build RecyclerView     private void buildRecyclerView() {         // creating a new array list         courseModelArrayList = new ArrayList<>();          // adding data to the 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 the adapter class         adapter = new CourseAdapter(courseModelArrayList, MainActivity.this);          // adding layout manager to the RecyclerView         LinearLayoutManager manager = new LinearLayoutManager(this);         courseRV.setHasFixedSize(true);          // setting layout manager to the RecyclerView         courseRV.setLayoutManager(manager);          // setting adapter to the RecyclerView         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)         toolbar = findViewById<Toolbar>(R.id.toolbar)          // setting the toolbar as the ActionBar         setSupportActionBar(toolbar)          // 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     } } 


Step 8: Update themes.xml

In the newer versions of Android Studio, the action bar is removed by default. To change that, navigate to app > res > values > themes.xml and update the base theme style

Before

<style name="Base.Theme.Demo" parent="Theme.Material3.DayNight.NoActionBar">

After

<style name="Base.Theme.Demo" parent="Theme.Material3.DayNight">

Click Here to get the full Project for SearchView with RecyclerView

Output:



Next Article
SearchView in Android with RecyclerView

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Kotlin
  • Android
  • Technical Scripter 2020
  • Kotlin Android
  • Java-Android
Practice Tags :
  • Java

Similar Reads

    Android - SearchView with RecyclerView using Kotlin
    Many apps display vast amounts of data within their in the form of a list and the user is not able to go through each item within the list to get the item that he wants. For filtering these lists within the android application we can use SearchView to filter it. In this article, we will be building
    7 min read
    SearchView in Android with ListView
    SearchView is a widget provided by the Android framework that allows users to search for specific data within an application. It is commonly used in apps that have large amounts of data or content that can be searched, such as contacts, music, or emails. The SearchView widget consists of an input fi
    2 min read
    SearchView in Android with Kotlin
    SearchView is a widget in android which provides a search interface with the help of which users can be able to make searches within the given list of data. In this search view, the user has to specify the search query. According to the search, query results will be populated within the listview. In
    4 min read
    RecyclerView in Android with Example
    RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be custo
    7 min read
    Android - RecyclerView as Staggered Grid with Kotlin
    Staggered Grid View has been seen in most applications such as Pinterest in which each item of grid view takes its own height and aligns within the grid view according to that. In this article, we will look at how to implement Staggered Grid Layout Manager to our Recycler View in Android. Note: If y
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences