How to use SearchView in the Toolbar in Kotlin?

Kotlin Apps/ApplicationsMobile Development

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.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   tools:context=".MainActivity">
   <androidx.appcompat.widget.Toolbar
   android:id="@+id/toolbar"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:background="?attr/colorBackgroundFloating"
   android:minHeight="?attr/actionBarSize" />
   <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/emptyView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="No Results"
      android:textSize="20sp"
      android:visibility="gone" />
</RelativeLayout>

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

<resources>
   <string name="app_name">Q38</string>
   <string-array name="months_array">
      <item>January</item>
      <item>February</item>
      <item>March</item>
      <item>April</item>
      <item>May</item>
      <item>June</item>
      <item>July</item>
      <item>August</item>
      <item>September</item>
      <item>October</item>
      <item>November</item>
      <item>December</item>
   </string-array>
</resources>

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: ArrayAdapter<*>
   private 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<Any?>(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−

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto">
   <item
      android:id="@+id/appSearchBar"
      android:icon="@drawable/ic_search"
      android:title="Search"
      app:actionViewClass="android.widget.SearchView"
      app:showAsAction="ifRoom|withText" />
</menu>

Step 6 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.q36">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

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 −

Click here to download the project code.

raja
Published on 21-Apr-2020 10:04:03
Advertisements