Kotlin Android - Search/Filter ListView with SearchView

| Page Views: 1237

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

Add this code to the the project level build.gradle file. We are registering the jitpack.io as our repository under the repositories DSL.

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

Then add the dependency to the the app level build.gradle file :

    implementation 'com.github.mancj:MaterialSearchBar:0.7.6'

Then in your layout add:

<com.mancj.materialsearchbar.MaterialSearchBar
        style="@style/MaterialSearchBarLight"
        app:mt_speechMode="true"
        app:mt_hint="Custom hint"
        app:mt_maxSuggestionsCount="10"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchBar" />

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 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: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:

Kotlin Android ListView Search Filter

Kotlin Android ListView MaterialSearchBar

Top Android SearchView Types Examples

Let's look at some examples.

Android Custom ListView with Images and Text Search Filter

How to search filter a custom ListView with images and text using a searchview. Our adapter is BaseAdapter.

Android Custom ListView Search/Filter and ItemClickListener tutorial.

In this piece we see how to search/filter a ListView then handle the itemClick events for the searched cardviews.

Android Custom RecyclerView with Images and Text Search/Filter.

This is an android tutorial to explore how to search or filter a recyclerview with images and text.

Android Material SearchBar Tutorial and Example.

  • How to use a Material SearchView inside a Searchbar and show search history.
  • The user can select search history as suggestions instead of typing again.
  • In this case we stored the search history in a simple arraylist.

Android Material SearchView and History Tutorial and Example.

  • Here the purpose is to programmatically open search,close and show search suggestions while searching.
  • The search occurs in a nice fragment.
  • We use a Material SearchView library.

Android Material ToolBar SearchBar/SearchView Example - How to filter search a simple GridView.

Android Material ToolBar SearchBar/SearchView Example - How to filter search a simple ListView and handle onclicks.

===

So let's see how to filter/search a simple ListView from the toolbar using a material design searchbar. We'll place our searchbar/searchview in the appbar and filter our listv...

Android RecyclerView Search/Filter and OnClick Tutorial and Example.

This is an android tutorial to explore how to search or filter a recyclerview with images and text.

Android RecyclerView MaterialSearchBar Search Filter.

We had done a tutorial some months later about Search/Filter with recyclerView. However, that was with the searchview as our search form. Today we see how to search filter with material searchbar as the search component. User will perform realtime search filter. As they type we filter the cards based on the search term. Our recyclerview comprises of material cardviews. We populate our recyclerview via an arraylist of strings. Let's go.

Android Simple ListView Search/Filter Tutorial and Example.

How to search or filter a simple ListView in android.

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

Best Regards, Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post