Android SearchView Using Kotlin With Example

In this article, we will learn about android SearchView using Kotlin. We will go through various example that demonstrates how to use different attributes of SearchView. For example,

In this article, we will get answer to questions like –

  • What is SearchView?
  • Why should we consider SearchView while designing ui for any app?
  • What are possibilities using SearchView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin Android SearchView Using Kotlin With Example

Getting Started

We can define android SearchView widget as below –

SearchView is a widget that provides a way to search element from list.

Now, how do we use SearchView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as SearchView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android SearchView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using SearchView in Kotlin

Follow steps below to use SearchView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">SearchView</string>
        <string name="no_match">No match found</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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"
        android:padding="20dp"
        tools:context=".MainActivity">
    
        <SearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Enter some text..."
            app:layout_constraintStart_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="20dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/searchView" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    In activity_main.xml file, We have used –

    1. SearchView: SearchView provides a way to search some text. You can enter text and apply search.
    2. ListView: ListView contains list of items we are applying filter on.
  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.searchview
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.ArrayAdapter
    import android.widget.Toast
    import androidx.appcompat.widget.SearchView
    import com.tutorialwing.searchview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    	private lateinit var adapter: ArrayAdapter<String>
    
    	val cityList =
    		listOf(
    			"America",
    			"India",
    			"Nepal",
    			"China",
    			"Sri Lanka",
    			"South Africa",
    			"Bangladesh",
    			"England",
    			"Bhutan",
    			"Finland",
    			"Greenland"
    		)
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupListView()
    		setupSearchView()
    	}
    
    	private fun setupListView() {
    		adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, cityList)
    		binding.listView.adapter = adapter
    	}
    
    	private fun setupSearchView() {
    		binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener,
    			android.widget.SearchView.OnQueryTextListener {
    			override fun onQueryTextSubmit(p0: String?): Boolean {
    				val isMatchFound = cityList.contains(p0)
    				val msg = if (isMatchFound) "Found: $p0" else getString(R.string.no_match)
    				Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
    				return false
    			}
    
    			override fun onQueryTextChange(p0: String?): Boolean {
    				adapter.filter.filter(p0)
    				return false
    			}
    		})
    	}
    }
    
    1. cityList : It contains list of cities which we are displaying in listView.
    2. setupListView() : In this method, we are initialising an adapter and set it to listView.
    3. setupSearchView() : In this method, we have set query text listener. There are two overridden methods – (1) onQueryTextSubmit method is called when we are done with entering text in searchView and click on searchButton or press enter button., (2) onQueryTextChange method is called while we are entering text in searchView.

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android SearchView Using Kotlin With Example

Different Attributes of SearchView in XML

Now, we will see how to use different attributes of Android SearchView using Kotlin to customise it –

Set Id of SearchView

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of SearchView using android:id attribute like below –

    <SearchView
        android:id="@+id/searchView_ID"
        />

Here, we have set id of SearchView as searchView_ID using android:id=”” attribute. So, if we need to reference this SearchView, we need to use this id – searchView_ID.
Learn to Set ID of SearchView Dynamically

Set Width of SearchView

We use android:layout_width=”” attribute to set width of SearchView.
We can do it as below –

    <SearchView
        android:id="@+id/searchView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of SearchView Dynamically

Set Height of SearchView

We use android:layout_height=”” attribute to set height of SearchView.
We can do it as below –

    <SearchView
        android:id="@+id/searchView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of SearchView Dynamically

Set Padding of SearchView

We use android:padding=”” attribute to set padding of SearchView.
We can do it as below –

    <SearchView
        android:id="@+id/searchView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in SearchView using android:padding=”” attribute.
Learn to Set Padding of SearchView Dynamically

Set Margin of SearchView

We use android:layout_margin=”” attribute to set margin of SearchView.
We can do it as below –

    <SearchView
        android:id="@+id/searchView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in SearchView using android:layout_margin=”” attribute.
Learn to Set Margin of SearchView Dynamically

Set Background of SearchView

We use android:background=”” attribute to set background of SearchView.
We can do it as below –

    <SearchView
        android:id="@+id/searchView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in SearchView using android:background=”” attribute.
Learn to Set Background of SearchView Dynamically

Set Visibility of SearchView

We use android:visibility=”” attribute to set visibility of SearchView.
We can do it as below –

    <SearchView
        android:id="@+id/searchView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of SearchView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of SearchView Dynamically

Different Attributes of Android SearchView Widget

Below are the various attributes that are used to customise android SearchView Widget. However, you can check the complete list of attributes of SearchView in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of ScrollView inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Defines whether LayoutTransition should run whenever there is any changes in layout
2 android:animationCache Defines whether layout animations should create a drawing cache for their children.
3 android:clipToPadding Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero.
4 android:layoutAnimation Defines the layout animation to use the first time the ViewGroup is laid out
5 android:layoutMode Defines the layout mode of this viewGroup

Some of the popular attributes of android ScrollView inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines the alpha of the view
2 android:background Defines the background of the view
3 android:padding Defines padding of the view for all edges
4 android:tooltipText Defines text displayed in a small popup window on hover or long press
5 android:clickable Defines whether view is clickable or not
6 android:theme Defines a theme override for view
7 android:id Defines id of the view
8 android:padding Defines padding of the view

We have seen different attributes of SearchView and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is SearchView, how can we use android SearchView using Kotlin ? etc. We also went through different attributes of android SearchView.

Leave a Reply