SearchView in Android with Kotlin
Last Updated :
28 Jul, 2022
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 this article, we will take a look at How to implement SearchView in Android ListView in Kotlin. We will be building a simple application in which we will be displaying the list of programming languages within listview. We will be also displaying a search view with which users can filter the data within the list view according to the search query. A sample video is given below to get an idea about what we are going to do in this article.
Note: To implement Search View in Android using Java, check out the following article: Search View in Android ListView in 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. 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">
<!--Search view for filtering list view-->
<SearchView
android:id="@+id/idSV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:iconifiedByDefault="false"
android:padding="4dp"
android:queryHint="Search Programming language" />
<!--List View from which data is to be searched
for different programming languages-->
<ListView
android:id="@+id/idLVProgrammingLanguages"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/idSV" />
</RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt 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.widget.ArrayAdapter
import android.widget.ListView
import android.widget.SearchView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
// on below line we are
// creating variables for listview
lateinit var programmingLanguagesLV: ListView
// creating array adapter for listview
lateinit var listAdapter: ArrayAdapter<String>
// creating array list for listview
lateinit var programmingLanguagesList: ArrayList<String>;
// creating variable for searchview
lateinit var searchView: SearchView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initializing variables of list view with their ids.
programmingLanguagesLV = findViewById(R.id.idLVProgrammingLanguages)
searchView = findViewById(R.id.idSV)
// initializing list and adding data to list
programmingLanguagesList = ArrayList()
programmingLanguagesList.add("C")
programmingLanguagesList.add("C#")
programmingLanguagesList.add("Java")
programmingLanguagesList.add("Javascript")
programmingLanguagesList.add("Python")
programmingLanguagesList.add("Dart")
programmingLanguagesList.add("Kotlin")
programmingLanguagesList.add("Typescript")
// initializing list adapter and setting layout
// for each list view item and adding array list to it.
listAdapter = ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
programmingLanguagesList
)
// on below line setting list
// adapter to our list view.
programmingLanguagesLV.adapter = listAdapter
// on below line we are adding on query
// listener for our search view.
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
// on below line we are checking
// if query exist or not.
if (programmingLanguagesList.contains(query)) {
// if query exist within list we
// are filtering our list adapter.
listAdapter.filter.filter(query)
} else {
// if query is not present we are displaying
// a toast message as no data found..
Toast.makeText(this@MainActivity, "No Language found..", Toast.LENGTH_LONG)
.show()
}
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
// if query text is change in that case we
// are filtering our adapter with
// new text on below line.
listAdapter.filter.filter(newText)
return false
}
})
}
}
Now run your application to see the output of it.Â
Output:Â
Similar Reads
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
Retrofit with Kotlin Coroutine in Android Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Introduction to Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Data Types The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin when expression In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
Kotlin Constructor A constructor is a special member function that is automatically called when an object of a class is created. Its main purpose is to initialize properties or perform setup operations. In Kotlin, constructors are concise, expressive, and provide significant flexibility with features like default para
6 min read
Android RecyclerView in Kotlin In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
4 min read
ProgressBar in Android Progress Bar are used as loading indicators in android applications. These are generally used when the application is loading the data from the server or database. There are different types of progress bars used within the android application as loading indicators. In this article, we will take a lo
3 min read
Kotlin Array An Array is one of the most fundamental data structures in practically all programming languages. The idea behind an array is to store multiple items of the same data type, such as an integer or string, under a single variable name. Arrays are used to organize data in programming so that a related s
6 min read