SearchView implementation in ListView using Kotlin in Android Studio

Introduction

SearchView is a real- time responsive filtration method which helps user to sort required item from list using characters. Android SearchView requires onQueryChange and onQuerySubmit to register inputs. In this tutorial we’ll be creating a ListView which SearchView feature which redirects to next Activity.

Setup Project

Create a new Project in Android Studio, use Kotlin as language. once Gradle is loaded, create a new kotlin activity, and name it SecondActivity. SecondActivity will be opened when user taps on any item of ListView. Now, create a XML layout file inside layout folder for SecondActivity and name it second_activity. Add the code given below in SecondActivity.kt to register your XML layout file.

class SecondActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second_activity)
}
}

Design your Layout

Open activity_main.xml located in Layout folder, and the code given below

<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lv_ListView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

Here, we are adding a ListView with ID lv_Listview. This will format a ListView with text fields in it.

Once done, open second_acitivity.xml and add the code given below.

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product information"
android:textSize="33sp"
tools:layout_editor_absoluteX="58dp"
tools:layout_editor_absoluteY="343dp" />

This will add a simple TextView with text as “Product information”. This will act a static page.

Add Data

There are multiple ways to store data in android, array, list, viewmodel etc. For this tutorial, we are using String resource file. To add data in String Resource file, extend Values folder inside res folder, and open strings.xml. Now add the code given below.

<resources>
<string name="app_name">SearchInListView</string>
<string-array name="product_array">
<item>Samsung LED TV</item>
<item>LG LED TV</item>
<item>Sony LED TV</item>
<item>LG Laptop</item>
<item>Samsung Music System</item>
<item>LG Laptop</item>
</string-array>
</resources>

Here, we are creating string-array to store items.

Add SearchView Button

SearchView button requires an image available in drawables folder. There are plenty of in-built clip art already available in Android Studio. We will be considering one of them in this tutorial. Create a new Vector Asset inside drawable folder. Click on Clip art and search “search“. Select the magnifying glass clip art. Name it ic_search.

To add SearchView button on the toolbar, we will first create a folder and name it menu in the res folder directory. Now, create a new menu resource file inside menu folder and name it nav_menu. Once done, open the file and paste the below given 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/nav_search"
android:icon="@drawable/ic_search"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="ifRoom|withText"/>
</menu>

Above code will add search button in toolbar. Next step is to integrate search functionality.

ListView in MainActivity

Open MainActivity.kt and add the code given below.

class MainActivity : AppCompatActivity() {
    private lateinit var adapter: ArrayAdapter<*>
    private lateinit var lv_listView: ListView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,resources.getStringArray(R.array.product_array))
        lv_listView = findViewById(R.id.lv_ListView)
        lv_listView.adapter = adapter
        lv_listView.onItemClickListener =AdapterView.OnItemClickListener{parent, view, position, id -> val intent = Intent(parent.context,SecondActivity::class.java)
            //Use intent.putExtra to send data from this activity, Learn more about intent.putExtra on BasicCodist.wordpress.com
            parent.context.startActivity(intent)}
    }
}

Here, we are creating an ArrayAdapter for listing data in the ListView.

adapter is the reference to ArrayAdapter which registers the data available in strings.xml and assigns it in simple list format.

Now, we have assigned ListView of MainActivity to adapter which then assigns the data.

lv_listView.onItemClickListener will help is getting the selected item from user, to which we have assigned StartActivity() which will start the next activity.

Add SearchView function

Open MainActivity.kt and add the function given below in MainActivity class.

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.nav_menu,menu)

val search = menu?.findItem(R.id.nav_search)
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)
}

This function will create search menu in the toolbar.

Here, we are focusing on onQueryTextChange which will filter items from adapter according to newText, which is the keyboard input provided by user.

Now Save and Run.

Where To Go From Here?

Try pushing data using intent putExtra. Read intent putExtra article to learn more.

Written by

XR Developer responsible for end-to-end development of XR solutions spanning multiple domains, by using various XR and WebXR libraries.

1 thought on “SearchView implementation in ListView using Kotlin in Android Studio

Leave a Reply