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 Material SearchBar ListView Project Structure
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
- We use Material SearchBar library https://github.com/mancj/MaterialSearchBar by Mansur.
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 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 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.
How To Run
- Download the project above.
- You’ll get a zipped file,extract it.
- Open the Android Studio.
- Now close, already open project.
- From the Menu bar click on File >New> Import Project.
- Now Choose a Destination Folder, from where you want to import project.
- Choose an Android Project.
- Now Click on “OK“.
- Done, your done importing the project,now edit it.
More
YouTube
- Visit our channel for more examples like these.
- Lets share tips and ideas in our Facebook Page.
Oclemy,Cheers.