Android Material ToolBar SearchBar - Search/Filter ListView

android search filter

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 listview in realtime as the user types data in the searchbar.

We use ArrayAdapter to populate our ListView from a simple arraylist. This then helps us in filtering as the arrayadpter instance gives us a Filter object that helps us easily implement a basic filter.

Screenshot

  • Here's the screenshot of the project.

Android ToolBar SearchBar ListView

Android ToolBar SearchBar ListView

Android ToolBar Material SearchBar ListView Project Structure

Android ToolBar Material SearchBar

Common Questions this example explores

  • Android Material ToolBar SearchBar ListView example.
  • Android Filter or Search a ListView.
  • Realtime search listview using searchview.

Tools Used

This example was written with the following tools:

  • Windows 8
  • AndroidStudio IDE
  • Genymotion Emulator
  • Language : Java
  • Topic : Material SearchBar, ToolBar SearchBar, ListView Search Filter

Libaries Used

Source Code

Lets jump directly to the source code. [su_tabs] [su_tab title="Build.Gradle Project Level"]

  • Our project level build.gradle.
  • We add repositories for fetching our dependencies here.
  • The dafult,jccenter() is already specified.
  • However, we add the maven and specify the url we'll use to fetch our Material SearchBar here.
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Build.Gradle App Level

  • Our app level build.gradle file.
  • We specify compilesdk,minimum sdk,target sdk and dependencies.
  • Note that the minimum sdk must be API level 16 Jelly bean for us to use the Material Searchbar library that we use here.
  • We also add dependencies using 'compile' statement.
  • Our activity shall derive from the appCompatActivity to make it target earlier android versions.
  • We also specify design support library.
  • Finally we add the com.github.mancj:MaterialSearchBar which is a third party library we'll use to display Material Searchbar.
  • You then sync the project.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.tutorials.hp.searchbarlistview"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:design:25.3.1'
    compile 'com.github.mancj:MaterialSearchBar:0.7.1'
}

MainActivity.java

  • Our MainActivity class.
  • Derives from AppCompatActivity which is a Base class for activities that use the support library action bar features.
  • Methods: onCreate().
  • Inflated From activity_main.xml using the setContentView() method.
  • This method is responsible for filtering/searching a gridview via a material serahcbar displayed inside a toolbar.
  • The views we use are Material Searchbar for searching and GridView to be searched.
  • Reference MaterialSearchBar and GridView from our layout specification using findViewById().
  • Instantiate adapter and set it to GridView.
  • Add TextChangeListener to MaterialSearchBar and use arrayadapter instance to filter data.
package com.tutorials.hp.searchbarlistview;

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

public class MainActivity extends AppCompatActivity {

    /*
    - When activity is created.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        List<String> galaxies=new ArrayList<>();
        galaxies.add("Cartwheel");
        galaxies.add("Whirlpool");
        galaxies.add("Andromeda I");
        galaxies.add("Andromeda II");
        galaxies.add("Sombrero");
        galaxies.add("Messier 81");
        galaxies.add("Messier 87");
        galaxies.add("Canis Majos Over-density");
        galaxies.add("Messier 92");
        galaxies.add("Black Eye");
        galaxies.add("Centaurus A");
        galaxies.add("Centaurus B");
        galaxies.add("Milky Way");
        galaxies.add("IC 1011");
        galaxies.add("Star Bust");
        galaxies.add("Hoag's Object");
        galaxies.add("Pinwheel");
        galaxies.add("Triangulum");
        galaxies.add("Cosmos Redshift");
        galaxies.add("Ursa Minor");
        galaxies.add("Virgo Stellar-Stream");

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

        //SEARCHBAR TEXT CHANGE LISTENER
        searchBar.addTextChangeListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //SEARCH FILTER
                adapter.getFilter().filter(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //LISTVIEW ITEM CLICKED
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, adapter.getItem(i).toString(), Toast.LENGTH_SHORT).show();
            }
        });

    }

}

ActivityMain.xml

  • ActivityMain.xml.
  • This is a template layout for our MainActivity.
  • Root layout tag is CoordinatorLayout from design support library.
  • CordinatorLayout is viewgroup that is a superpowered on framelayout.
  • CoordinatorLayout is intended for two primary use cases: As a top-level application decor or chrome layout As a container for a specific interaction with one or more child views
  • Inside our CordinatorLayout we add : AppBarLayout,FloatingActionButton and include content_main.xml.
  • AppBarLayout is vertical LinearLayout that implements scrolling features of material design concept.
  • It should be a direct child of CordinatorLayout, otherwise alot of features won't work.
  • Inside the AppBarLayout we add our toolbar,which we give a blue color.
  • Next we add our Material SearchBar which will give us the searchbar.
  • We can specify attributes like style and hint.
  • We will add our widgets in our content_main.xml, not here as this is a template layout.
  • Finally we have a FloatingActionButton, a class that derives from android.support.design.widget.VisibilityAwareImageButton. Its the round button you see in our user interface.
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout 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="com.tutorials.hp.searchbarlistview.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <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" />
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

ContentMain.xml

  • Our ContentMain.xml file.
  • Shall get inflated to MainActivity.
  • Root tag is relativeLayout.
  • Contains ListView with two columns.
  • It is this ListView that we shall be searching.
<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.searchbarlistview.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/mListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</android.support.constraint.ConstraintLayout>

 

Video/Preview

  • We have a YouTube channel with almost a thousand tutorials, this one below being one of them.

https://www.youtube.com/watch?v=BuEQ1m9nnQI

Download

  • You can Download the full Project below. Source code is well commented.

Download

How To Run

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.

More

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.

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. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post