Android studio kotlin search

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.

Читайте также:  Python requests urlencode params

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.

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

Источник

Читайте также:  Java create random string

How to use SearchView in the Toolbar in Kotlin?

This example demonstrates how to use SearchView in the Toolbar in Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Open res/strings.xml and add the following code−

 Q38 January February March April May June July August September October November December  

Step 4 − Add the following code to MainActivity.kt

import android.os.Bundle import android.view.Menu import android.widget.* import android.widget.AdapterView.OnItemClickListener import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() < private lateinit var toolbar: Toolbar lateinit var adapter: ArrayAdapterprivate lateinit var listView: ListView private lateinit var emptyView: TextView override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" toolbar = findViewById(R.id.toolbar) listView = findViewById(R.id.listView) emptyView = findViewById(R.id.emptyView) adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, resources.getStringArray(R.array.months_array)) listView.adapter = adapter listView.onItemClickListener = OnItemClickListener < adapterView, _, i, _ ->Toast.makeText(this@MainActivity, adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show() > listView.emptyView = emptyView > override fun onCreateOptionsMenu(menu: Menu): Boolean < menuInflater.inflate(R.menu.menu, menu) val search = menu.findItem(R.id.appSearchBar) val searchView = search.actionView as SearchView searchView.queryHint = "Search" searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener < override fun onQueryTextSubmit(query: String?): Boolean < return false >override fun onQueryTextChange(newText: String?): Boolean < adapter.filter.filter(newText) return true >>) return super.onCreateOptionsMenu(menu) > >

Step 5 − Create a Android resource folder (menu) and create a menu resource file (menu.xml) and add the following code−

Step 6 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Читайте также:  Java first not null

Click here to download the project code.

Источник

How to use SearchView in Android Kotlin?

This example demonstrates how to use SearchView in Android Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle import android.widget.ArrayAdapter import android.widget.ListView import android.widget.SearchView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() < lateinit var searchView: SearchView lateinit var listView: ListView lateinit var list: ArrayListlateinit var adapter: ArrayAdapter override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" searchView = findViewById(R.id.searchView) listView = findViewById(R.id.listView) list = ArrayList() list.add("Apple") list.add("Banana") list.add("Pineapple") list.add("Orange") list.add("Mango") list.add("Grapes") list.add("Lemon") list.add("Melon") list.add("Watermelon") list.add("Papaya") adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list) listView.adapter = adapter searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener < override fun onQueryTextSubmit(query: String): Boolean < if (list.contains(query)) < adapter.filter.filter(query) >else < Toast.makeText(this@MainActivity, "No Match found", Toast.LENGTH_LONG).show() >return false > override fun onQueryTextChange(newText: String): Boolean < adapter.filter.filter(newText) return false >>) > >

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Источник

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