Android Material ToolBar SearchBar - Filter/Search GridView

October 27, 2017 Oclemy Android SearchView, Android GridView 7 minutes, 11 seconds

Android Material ToolBar SearchBar/SearchView Example - How to filter search a simple GridView. It's true we have looked at several searchview examples previously. However, we have been using the ordinary searchview that we normally display in our content section. A more popular approach is using a searchview/searchbar placed in the toolbar or appbar of our activity. It's what we look at in this example. We use a toolbar searchbar to search/filter our simple GridView.

Screenshot

  • Here's the screenshot of the project.

Android ToolBar SearchBar Android ToolBar SearchBar Android ToolBar Material SearchBar Project Structure Android ToolBar Material SearchBar

Common Questions this example explores

  • Android Material ToolBar SearchBar example.
  • Android Filter Search a GridView.

Tools Used

This example was written with the following tools:

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

Libaries Used

Source Code

Lets jump directly to the source code.

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.searchbargridview"
        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.searchbargridview;

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.GridView;
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);

        //INITIALIZE GRIDVIEW AND MATERIAL SEARCHBAR
        GridView gv= (GridView) findViewById(R.id.mGridView);
        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);
        gv.setAdapter(adapter);

        //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) {

            }
        });

        //HANDLE GRIDVIEW ITEM CLICK
        gv.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.searchbargridview.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 GridView with two columns.
  • It is this gridview 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.searchbargridview.MainActivity"
    tools:showIn="@layout/activity_main">

    <GridView
        android:id="@+id/mGridView"
        android:numColumns="2"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </GridView>

</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=JjwwrCS8Xmc

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.

Comments