Android recyclerview search kotlin

How to add Search in RecyclerView using Kotlin

Today, I will show you how to search for items in a RecyclerView using SearchView.

In this example, we have a RecyclerView already set up, and the only thing we do is to add the searching functionality.

We have a list of countries as sample data and using the search field we get the country we want faster.

Adding SearchView in RecyclerView

Add the SearchView in your layout, inside a LinearLayout with a vertical orientation.

 LinearLayout 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:id="@+id/country_content_id" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimaryDark" android:orientation="vertical" tools:context=".MainActivity"> androidx.appcompat.widget.SearchView android:id="@+id/country_search" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:textCursorDrawable="@null" app:iconifiedByDefault="false" app:queryBackground="@null" /> androidx.recyclerview.widget.RecyclerView android:id="@+id/country_rv" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimaryDark" /> LinearLayout>Code language: HTML, XML (xml)

In the RecyclerView adapter (In this example, RecyclerViewAdapter.kt), create an ArrayList with the name countryFilterList, and pass all the items…

class RecyclerViewAdapter(private var countryList: ArrayList) : RecyclerView.Adapter() < var countryFilterList = ArrayList() init < countryFilterList = countryList >// . >Code language: Kotlin (kotlin)

Return the size of countryFilterList so every time will return the right amount of items that match the characters you type in the SearchView.

class RecyclerViewAdapter(private var countryList: ArrayList) : RecyclerView.Adapter() < // . override fun getItemCount(): Int < return countryFilterList.size > // . >Code language: Kotlin (kotlin)

Now, in the onBindViewHolder get the item for each row from the countryFilterList array.

class RecyclerViewAdapter(private var countryList: ArrayList) : RecyclerView.Adapter() < // . override fun onBindViewHolder(holder: CountryViewHolder, position: Int) < // . val selectCountryTextView = holder.itemView.findViewById(R.id.select_country_text_view) selectCountryTextView.text = countryFilterList[position] // . > >Code language: Kotlin (kotlin)

Add the Filterable class in the RecyclerViewAdapter and the method getFilter()

class RecyclerViewAdapter(private var countryList: ArrayList) : RecyclerView.Adapter(), Filterable < override fun getFilter(): Filter < >>Code language: Kotlin (kotlin)

Inside the getFilter() method, return a Filter() object:

class RecyclerViewAdapter(private var countryList: ArrayList): RecyclerView.Adapter(), Filterable < override fun getFilter(): Filter < return object : Filter() < override fun performFiltering(constraint: CharSequence?): FilterResults < >@Suppress("UNCHECKED_CAST") override fun publishResults(constraint: CharSequence?, results: FilterResults?) < >> > >Code language: Kotlin (kotlin)

The performFiltering method checks if we have typed a text in the SeachView.

If there is not any text, will return all items.

If there is a text, then we check if the characters match the items from the list and return the results in a FilterResults type.

Читайте также:  Javascript functions in html page

The publishResults get these results, pass them to the countryFilterList array, and update the RecyclerView.

class RecyclerViewAdapter(private var countryList: ArrayList) : RecyclerView.Adapter(), Filterable < override fun getFilter(): Filter < return object : Filter() < override fun performFiltering(constraint: CharSequence?): FilterResults < val charSearch = constraint.toString() if (charSearch.isEmpty()) < countryFilterList = countryList >else < val resultList = ArrayList() for (row in countryList) < if (row.lowercase(Locale.ROOT) .contains(charSearch.lowercase(Locale.ROOT)) ) < resultList.add(row) >> countryFilterList = resultList > val filterResults = FilterResults() filterResults.values = countryFilterList return filterResults > @Suppress("UNCHECKED_CAST") override fun publishResults(constraint: CharSequence?, results: FilterResults?) < countryFilterList = results?.values as ArrayList notifyDataSetChanged() > > > >Code language: Kotlin (kotlin)

Go back to the Activity file (MainActivity.kt) and add the setOnQueryTextListener.

class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // . country_search.setOnQueryTextListener(object: SearchView.OnQueryTextListener< override fun onQueryTextSubmit(query: String?): Boolean < return false > override fun onQueryTextChange(newText: String?): Boolean < adapter.filter.filter(newText) return false > >) // . > >Code language: Kotlin (kotlin)

The onQueryTextChange method is called every time we type on the SearchView and update the RecyclerView with the new results.

Customizing the SearchView

If you want to change the color of the search icon (magnifying glass):

class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // . val countrySearch = findViewById(R.id.country_search) val searchIcon = countrySearch.findViewById(androidx.appcompat.R.id.search_mag_icon) searchIcon.setColorFilter(Color.WHITE) // . > >Code language: Kotlin (kotlin)

For the color of the cancel button:

class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // . val cancelIcon = countrySearch.findViewById(androidx.appcompat.R.id.search_close_btn) cancelIcon.setColorFilter(Color.WHITE) // . > >Code language: Kotlin (kotlin)

And to change the text color of the TextView:

class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // . val textView = countrySearch.findViewById(androidx.appcompat.R.id.search_src_text) textView.setTextColor(Color.WHITE) // If you want to change the color of the cursor, change the 'colorAccent' in colors.xml // . > >Code language: Kotlin (kotlin)

If you have any questions, please feel free to leave a comment below

Источник

Android recyclerview search kotlin

Card image cap

Table of Contents:

  1. Demo
  2. Introduction
  3. What is a SearchView?
  4. An Example:
    1. Dependencies
    2. Designing Activity Layout
    3. Model
    4. Designing List Layout
    5. Implementing Search in Adapter class
    6. Complete Recyclerview Adapter Class
    7. Adding the Recyclerview in Activity
    8. onQueryTextChangeListener

    Demo

    Introduction

    In this blog I’m going to show you how to filter a RecyclerView using a SearchView on Android

    What is a SearchView?

    SearchView : A SearchView is a widget used to capture text input. Usually it gets placed inside a Toolbar. That text input can then be used for a number of different tasks. In this blog post I’m going to show you how to use a SearchView to filter results in a RecyclerView.

    For more information on RecyclerView’s, check out this blog post: RecyclerView

    Dependencies

    Open build.gradle (Module:app) and add RecyclerView dependency.

    Make sure you have the latest version of dependencies. You can check the latest version here

    Designing MainActivity Layout

    Add the following code in your activity_main.xml file. This layout contains SearchView and a RecyclerView. SearchView is a widget that provides a user interface for the user to enter a search query and submit a request to a search provider

    Model

    Make a model class Name.java and put the following code inside it. This model class denotes name as the data member which contains the animal name

    Designing List Layout

    To display the Animals Name on the screen, we need to design the layout of the list item. This layout file contains the one TextView which will display the name of the Animal

    Implementing Search in Adapter class

    The First step is to implements the Filterable interface and override the getFilter() method and Declare the two List of type «Name» class. The first list is an initial list which contains all the elements and the second list (as the name suggests) will contain the items which are filtered according to the query typed in the Searchview and pass it in the constructor.

    The second step is to write search operation logic in getFilter() method. Inside getFilter() method, return an instance of Filter which will then Override two methods named performFiltering() and publishResults().

    This Method is invoke in a worker thread and it is used to filter the results according to the constraint specified. The main logic inside this method is that we are going through each object of Name class inside nameList and comparing the name of the animal with the query typed, If both becomes equal then we are adding the updated elements inside the new List named «filteredList» and assigning the «filteredList» to «filteredNameList» and at last we are returning the filtered results to the publishResults() method.

    Complete Recyclerview Adapter Class

    This is a complete Adapter class which contains the search logic which is explained above.

    Adding the Recyclerview in Activity

    Now, Declare all these objects inside MainActivity before onCreate() method and then, we will add some Animal Names to the list and set up the Adapter with RecyclerView inside onCreate() method.

    onQueryTextChangeListener

    Finallly, we will setup the SearchView inside the MainActivity. Paste the below code inside the onCreate() method of MainActivity. We are attaching the listener on SearchView and Overrriding two methods.

      onQueryTextSubmit(String queryString) :

    This method is invoked when then the search button is pressed to submit the query. In this method, we are passing the queryString to the filter() method which will start filtering the results according to the query passed.

    The complete code is available here.

    Staying in the Loop

    If you want to stay in the loop and get an email when I write new blog posts, Follow me on Instagram or join the CodingWithMitch community on my website. It only takes about 30 seconds to register.

    Источник

    Android recyclerview search kotlin

    Android Linear Layout Example with Kotlin | Android studioAndroid Searchview with RecyclerView Example | Android studio

    In this post we will cover how to implement searchview filter with recyclerview.

    How to add SeachView widget, We will add SearchView as an item to our options menu and make it expandable with the collapseActionView attribute

    • Add SearchView widget
    • Use SearchView inside Activity
    • Apply Search Filter inside Adapter

    Recyclerview with SearchView widget

    Add SearchView widget

    To add SearchView widget we will create menu item with passing Searchview widget as class name

    Use SearchView inside activity

    To use SearchiView we need to create searchview instance from menu item inside onCreateOptionsMenu()

    override fun onCreateOptionsMenu(menu: Menu?): Boolean < menuInflater.inflate(R.menu.example_menu,menu) var searchItem=menu?.findItem(R.id.action_search) var searchView=searchItem?.actionView as SearchView; searchView.setImeOptions(EditorInfo.IME_ACTION_DONE) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener < override fun onQueryTextSubmit(query: String?): Boolean < return false >override fun onQueryTextChange(newText: String?): Boolean < return false >>) return true >

    Apply Search Filter inside Adapter

    Implement adapter class with Filterable interface to handle search filter. This FIlterable has method getFilter() which will return the Filter() instance.

    In the Filter class we will implement search filter logic.

    Complete Example code for Recyclerview with SearchView Widget in Android Kotlin

    Activity class

    package com.rrtutors.androidtutorials import android.os.Bundle import android.view.Menu import android.view.inputmethod.EditorInfo import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_recyclerview_search.* class RecyclerviewSearch : AppCompatActivity() < lateinit var listData:ArrayList; lateinit var adapter:DataAdapter; override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_recyclerview_search) prepareData() init() >fun prepareData() < listData= ArrayList(); listData.add(ExampleData("String1 1","String2 1",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 2","String2 2",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 3","String2 3",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 4","String2 4",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 5","String2 5",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 6","String2 6",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 7","String2 7",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 8","String2 8",R.mipmap.ic_launcher)) listData.add(ExampleData("String1 9","String2 9",R.mipmap.ic_launcher)) > fun init() < recyclerview.layoutManager=LinearLayoutManager(applicationContext) adapter=DataAdapter(listdata = listData); recyclerview.adapter=adapter >override fun onCreateOptionsMenu(menu: Menu?): Boolean < menuInflater.inflate(R.menu.example_menu,menu) var searchItem=menu?.findItem(R.id.action_search) var searchView=searchItem?.actionView as SearchView; searchView.setImeOptions(EditorInfo.IME_ACTION_DONE) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener < override fun onQueryTextSubmit(query: String?): Boolean < return false >override fun onQueryTextChange(newText: String?): Boolean < adapter.getFilter().filter(newText) return false >>) return true > >

    Adapter class

    package com.rrtutors.androidtutorials import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.layout_data_item.view.* class DataAdapter(var listdata:ArrayList): RecyclerView.Adapter(), Filterable < lateinit var listdataSearch:ArrayListinit < listdataSearch= ArrayList() listdataSearch.addAll(listdata) >override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder < return DataViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.layout_data_item, parent, false) ); >override fun getItemCount(): Int < return listdataSearch.size >override fun onBindViewHolder(holder: DataViewHolder, position: Int) < holder.image_view.setImageResource(listdataSearch.get(position).img) holder.text_view1.text=listdataSearch.get(position).str1; holder.text_view2.text=listdataSearch.get(position).str2; >class DataViewHolder( itemView: View): RecyclerView.ViewHolder(itemView) < var text_view1=itemView.text_view1; var text_view2=itemView.text_view2; var image_view=itemView.image_view; >//class SearchFilter(val listdata:ArrayList): override fun getFilter(): Filter < return object : Filter() < override fun performFiltering(p0: CharSequence?): Filter.FilterResults < var listFilter=ArrayList(); if(p0==null||p0.isEmpty()) < listFilter.addAll(listdata) >else < val filterPattern: String = p0.toString().toLowerCase().trim() for (item in listdata) < if (item.str1.toLowerCase().contains(filterPattern)) < listFilter.add(item) >> > val results = Filter.FilterResults() results.values = listFilter return results; > override fun publishResults(p0: CharSequence?, p1: Filter.FilterResults?) < listdataSearch.clear() listdataSearch.addAll(p1?.values as Collection) notifyDataSetChanged() > > > >

    item_layout

    Источник

Оцените статью