Open In App

Android – SearchView with RecyclerView using Kotlin

Last Updated : 08 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 a simple application in which we will be implementing a Search View in Android Recycler View using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement Search View in Android with Recycler View using Java. Check out the following article: Search View in Android with Recycler View using Java

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. Note that select Kotlin as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating a
         text for heading of our app-->
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="18sp"
        android:textStyle="bold" />
 
    <!--on below line we are creating a recycler view-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/idTVHeading"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
 
</RelativeLayout>


Step 3: Creating a modal class for storing our data

Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class and name your class as CourseRVModal and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
data class CourseRVModal(
    // on below line we are creating a two variable
    // one for course name and other for course image.
    var courseName: String,
    var courseImg: Int
)


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
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="4dp">
   
    <!--on below line we are creating
        a linear layout for grid view item-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <!--on below line we are creating
             a simple image view-->
        <ImageView
            android:id="@+id/idIVCourse"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:padding="5dp"
            android:src="@mipmap/ic_launcher" />
 
        <!--on below line we are creating
             a simple text view-->
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:padding="4dp"
            android:text="@string/app_name"
            android:textAlignment="textStart"
            android:textColor="@color/black"
            android:textStyle="bold"
            tools:ignore="RtlCompat" />
 
    </LinearLayout>
 
</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 > Kotlin class and name it as CourseRVAdapter and add the below code to it. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
 
// on below line we are creating a course rv adapter class.
class CourseRVAdapter(
    // on below line we are passing variables as course list and context
    private var courseList: ArrayList<CourseRVModal>,
) : RecyclerView.Adapter<CourseRVAdapter.CourseViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CourseRVAdapter.CourseViewHolder {
        // this method is use to inflate the layout file
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        val itemView = LayoutInflater.from(parent.context).inflate(
            R.layout.course_rv_item,
            parent, false
        )
         
        // at last we are returning our view holder
        // class with our item View File.
        return CourseViewHolder(itemView)
    }
 
    // method for filtering our recyclerview items.
    fun filterList(filterlist: ArrayList<CourseRVModal>) {
        // below line is to add our filtered
        // list in our course array list.
        courseList = filterlist
        // below line is to notify our adapter
        // as change in recycler view data.
        notifyDataSetChanged()
    }
 
    override fun onBindViewHolder(holder: CourseRVAdapter.CourseViewHolder, position: Int) {
        // on below line we are setting data to our text view and our image view.
        holder.courseNameTV.text = courseList.get(position).courseName
        holder.courseIV.setImageResource(courseList.get(position).courseImg)
    }
 
    override fun getItemCount(): Int {
        // on below line we are returning
        // our size of our list
        return courseList.size
    }
 
    class CourseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // on below line we are initializing our course name text view and our image view.
        val courseNameTV: TextView = itemView.findViewById(R.id.idTVCourse)
        val courseIV: ImageView = itemView.findViewById(R.id.idIVCourse)
    }
}


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"?>
<menu
    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.kt file

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

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.RecyclerView
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating variables for
    // our swipe to refresh layout, recycler view,
    // adapter and list.
    lateinit var courseRV: RecyclerView
    lateinit var courseRVAdapter: CourseRVAdapter
    lateinit var courseList: ArrayList<CourseRVModal>
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // on below line we are initializing our views with their ids.
        courseRV = findViewById(R.id.idRVCourses)
 
        // on below line we are initializing our list
        courseList = ArrayList()
 
        // on below line we are initializing our adapter
        courseRVAdapter = CourseRVAdapter(courseList)
 
        // on below line we are setting adapter to our recycler view.
        courseRV.adapter = courseRVAdapter
 
        // on below line we are adding data to our list
        courseList.add(CourseRVModal("Android Development", R.drawable.android))
        courseList.add(CourseRVModal("C++ Development", R.drawable.c))
        courseList.add(CourseRVModal("Java Development", R.drawable.java))
        courseList.add(CourseRVModal("Python Development", R.drawable.python))
        courseList.add(CourseRVModal("JavaScript Development", R.drawable.js))
 
        // on below line we are notifying adapter
        // that data has been updated.
        courseRVAdapter.notifyDataSetChanged()
 
    }
 
    // 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: MenuItem = menu.findItem(R.id.actionSearch)
 
        // getting search view of our item.
        val searchView: SearchView = searchItem.getActionView() as SearchView
 
        // below line is to call set on query text listener method.
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener,
            android.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(p0: String?): Boolean {
                return false
            }
 
            override fun onQueryTextChange(msg: String): Boolean {
                // inside on query text change method we are
                // calling a method to filter our recycler view.
                filter(msg)
                return false
            }
        })
        return true
    }
 
    private fun filter(text: String) {
        // creating a new array list to filter our data.
        val filteredlist: ArrayList<CourseRVModal> = ArrayList()
 
        // running a for loop to compare elements.
        for (item in courseList) {
            // checking if the entered string matched with any item of our recycler view.
            if (item.courseName.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.
            courseRVAdapter.filterList(filteredlist)
        }
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads