This is a Kotlin android SearchView and ListView example. We see how to search/filter a simple ListView.

Users can simply type the search word or term and we search filter a listview.

We are using Kotlin as our programming language. We hold our data in a simple array.

But first let’s introduce some terms.

What is a MaterialSearchBar?

MaterialSearchBar is a beautiful and easy to use library will help to add Lollipop Material Design SearchView in your project.

Video Tutorial


Full Example

Let’s look at Code

How the App Works.

First we will have a ListView and MaterialSearchBar in our layouts. Then we will reference them in our java code using the findViewById function.

    val lv = findViewById(R.id.mListView) as ListView
    val searchBar = findViewById(R.id.searchBar) as MaterialSearchBar

Normally findViewById returns a view object which we can then cast to the specific widget using the as keyword.

Then we will create a simple array using the arrayOf() function. This will act as our data store or source.

        var galaxies = arrayOf("Sombrero", "Cartwheel", ....)

Then will prepare an adapter. In this case we use an arrayadapter as we are working with a simple array as the data source we will be searching.

        val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, galaxies)
        lv.setAdapter(adapter)

We will search our listview by listening to TextChange events on our searchbar. First we addTextChangeListener, then handle our events using three callback methods:

  1. beforeTextChanged
  2. onTextChanged – This is where we filter our adapter.
  3. afterTextChanged
            searchBar.addTextChangeListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                //SEARCH FILTER
                adapter.getFilter().filter(charSequence)
            }

            override fun afterTextChanged(editable: Editable) {

            }
        })

We will finally listen to listview click events after searching:

           lv.setOnItemClickListener(object : AdapterView.OnItemClickListener {
            override fun onItemClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
                Toast.makeText([email protected], adapter.getItem(i)!!.toString(), Toast.LENGTH_SHORT).show()
            }
        })

Let’s start coding.

1. Gradle Scripts

(a). build.gradle(app)

We will add MaterialSearchBar(com.github.mancj:MaterialSearchBar:0.7.1) as an implementation statement in our app level build.gradle.

Take note we are using kotlin so we will apply the kotlin-android plugin as well as the com.android.application.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.devosha.kotlinlistviewsearchbar"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.github.mancj:MaterialSearchBar:0.7.1'
}

2. Layouts

(a). activity_main.xml

Let’s add a MaterialSearchBar xml element and a ListView.

We are wrapping them in a LinearLayout with a vertical orientation.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical"
    tools_context=".MainActivity">

    <com.mancj.materialsearchbar.MaterialSearchBar
        app_mt_speechMode="true"
        app_mt_hint="Custom hint"
        app_theme="@style/AppTheme.PopupOverlay"
        app_mt_maxSuggestionsCount="5"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_id="@+id/searchBar" />
    <ListView
        android_id="@+id/mListView"
        android_layout_width="match_parent"
        android_layout_height="match_parent">
    </ListView>

</LinearLayout>

3. Kotlin Code

We write our code in Kotlin programming language.

(a). MainActivity.kt

Let’s look at our main activity.

package com.devosha.kotlinlistviewsearchbar

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.widget.Toast
import android.widget.AdapterView
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import com.mancj.materialsearchbar.MaterialSearchBar

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //REFERENCE MATERIALSEARCHBAR AND LISTVIEW
        val lv = findViewById(R.id.mListView) as ListView
        val searchBar = findViewById(R.id.searchBar) as MaterialSearchBar
        searchBar.setHint("Search..")
        searchBar.setSpeechMode(true)

        var galaxies = arrayOf("Sombrero", "Cartwheel", "Pinwheel", "StarBust", "Whirlpool", "Ring Nebular", "Own Nebular", "Centaurus A", "Virgo Stellar Stream", "Canis Majos Overdensity", "Mayall's Object", "Leo", "Milky Way", "IC 1011", "Messier 81", "Andromeda", "Messier 87")

        //ADAPTER
        val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, galaxies)
        lv.setAdapter(adapter)

        //SEARCHBAR TEXT CHANGE LISTENER
        searchBar.addTextChangeListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                //SEARCH FILTER
                adapter.getFilter().filter(charSequence)
            }

            override fun afterTextChanged(editable: Editable) {

            }
        })

        //LISTVIEW ITEM CLICKED
        lv.setOnItemClickListener(object : AdapterView.OnItemClickListener {
            override fun onItemClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
                Toast.makeText([email protected], adapter.getItem(i)!!.toString(), Toast.LENGTH_SHORT).show()
            }
        })

        //end

    }
}

Here are our results: