Hi guys. In this tutorial we will look at how to search filter data in android. We use primarily a searchview widget. We render data in various adapterviews like listview and recyclerview. We look at various examples.
Languages used:
- Kotlin
- Java
Concept 1: Android SearchView Tutorial and Examples
Example 1: Android Simple ListView – Search/Filter
Android Simple ListView Search/Filter Tutorial and Example.
How to search or filter a simple ListView in android.
Google search engine is the most visited website in the whole world. This tells us something about us humans and our need to always search and filter through information.
The worldwide web is really vast, and we cannot be able to use it conveniently by just remembering website urls or going through portals to find the content we want.
Instead we simply search. Now today we are not developing another search engine. Instead we look at a simple example in android, how to search through a list using searchview. Call it search or filter, but we find the information we want by typing it in the searchview. SearchView is a widget that was added to android in API 11.
It provides s imple edittext where user can enter a query and submit it to the search provider. For us we simply search through a simple listview using searchview.
Common Questions this example explores
- Android SearchView example.
- How to search a simple listview in android.
- Android SearchView arrayadapter example.
- How to search/filter in android.
This example was written with the following tools:
- Windows 8.1
- Eclipse IDE
- Java Language
- Bluestacks Emulator
Lets have a look at the source code.
MainActivity.java
Our MainActivity Class
Purpose :
- Reference our ListView and SearchView from xml
- Bind our data to ListView using ArrayAdapter.
- Handle our SearchView’s onQueryTextChangeListener.
- Filter or Search dynamically
package com.tutorials.simplelistviewfilter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class MainActivity extends Activity {
ListView lv;
SearchView sv;
String[] teams={"Man Utd","Man City","Chelsea","Arsenal","Liverpool","Totenham"};
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
sv=(SearchView) findViewById(R.id.searchView1);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,teams);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ActivityMain.xml
Our ActivityMain layout
Purpose
- Basically display whatever widgets we want to use,in this case ListView and SearchView.
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
tools_context=".MainActivity" >
<SearchView
android_id="@+id/searchView1"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_layout_alignParentLeft="true"
android_layout_alignParentTop="true"
android_queryHint="Search.."
>
</SearchView>
<ListView
android_id="@+id/listView1"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_layout_alignParentLeft="true"
android_layout_below="@+id/searchView1"
android_layout_marginTop="22dp" >
</ListView>
</RelativeLayout>
Video/Demo
How To Run
- This project was created by Eclipse.
- Therefore just copy the code and use in your project in android studio, it’s still android anyway and expandableListview is the same regardless of the IDE. So copy paste the code to your android studio project.
Example 2: Android Custom RecyclerView with Images and Text Search/Filter
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.
The RecyclerView will comprise CardViews so it is the CardViews that we will be filtering.
We use SearchView to input our search terms thus allowing us search in realtime.
Let’s go.
1. Create Basic Activity Project
- First create a new project in android studio. Go to File –> New Project.
- Type the application name and choose the company name.
- Choose minimum SDK.
- Choose Basic activity.
- Click Finish.
Basic activity will have a toolbar and floating action button already added in the layout
Normally two layouts get generated with this option:
No. | Name | Type | Description |
---|---|---|---|
1. | activity_main.xml | XML Layout | Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton. |
2. | content_main.xml | XML Layout | Will be included into activity_main.xml.You add your views and widgets here. |
3. | MainActivity.java | Class | Main Activity. |
2. Build.Gradle(App level)
We are not sung any special library.
3. Create User Interface
Here are our layouts for this project:
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
Here are some of the widgets, views and viewgroups that get employed"
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_fitsSystemWindows="true"
tools_context="com.tutorials.hp.customrecyclerfiltering.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" />
</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"
android_src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
(b). content_main.xml
This layout gets included in your activity_main.xml.
We add our SearchView on to of our RecyclerView here.
The SearchView will be used to Filter the RecyclerView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
app_layout_behavior="@string/appbar_scrolling_view_behavior"
tools_context="com.tutorials.hp.customrecyclerfiltering.MainActivity"
tools_showIn="@layout/activity_main">
<LinearLayout
android_layout_width="match_parent"
android_orientation="vertical"
android_layout_height="match_parent">
<android.support.v7.widget.SearchView
android_id="@+id/mSearch"
android_layout_width="match_parent"
android_layout_height="50dp"
app_defaultQueryHint="Search.."
></android.support.v7.widget.SearchView>
<android.support.v7.widget.RecyclerView
android_id="@+id/myRecycler"
android_layout_width="wrap_content"
android_layout_below="@+id/mSearch"
android_layout_height="wrap_content"
class="android.support.v7.widget.RecyclerView" />
</LinearLayout>
</RelativeLayout>
(c). model.xml
This is a CardView with various widgets. This layout will represent a single item in our RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_orientation="horizontal" android_layout_width="match_parent"
android_layout_margin="5dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="5dp"
android_layout_height="match_parent">
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent">
<ImageView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/playerImage"
android_padding="10dp"
android_src="@drawable/herera" />
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text="Name"
android_id="@+id/nameTxt"
android_padding="10dp"
android_layout_alignParentTop="true"
android_layout_toRightOf="@+id/playerImage" />
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceMedium"
android_text="Position"
android_id="@+id/posTxt"
android_padding="10dp"
android_layout_alignBottom="@+id/playerImage"
android_layout_alignParentRight="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
4. Player.java
This is our data object. Our POJO class.
This class represents a single Player.
public class Player {
private String name;
private String pos;
private int img;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
}
5. ItemClickListener.java
This an interface to define for us our event handler signature.
public interface ItemClickListener {
void onItemClick(View v,int pos);
}
6. MyHolder.java
This is a ViewHolder class.
It will hold our inflated model.xml
as a view object for recycling. This View will be used by the MyAdapter
class.
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//OUR VIEWS
ImageView img;
TextView nameTxt,posTxt;
ItemClickListener itemClickListener;
public MyHolder(View itemView) {
super(itemView);
this.img= (ImageView) itemView.findViewById(R.id.playerImage);
this.nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
this.posTxt= (TextView) itemView.findViewById(R.id.posTxt);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
this.itemClickListener.onItemClick(v,getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
}
7. MyAdapter.java
This is our RecyclerView.Adapter class.
This class will first inflate our model.xml
and bind data to the resultant view.
This class will also implement the android.widget.Filterable
interface.
public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable{
Context c;
ArrayList<Player> players,filterList;
CustomFilter filter;
public MyAdapter(Context ctx,ArrayList<Player> players)
{
this.c=ctx;
this.players=players;
this.filterList=players;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//CONVERT XML TO VIEW ONBJ
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
//HOLDER
MyHolder holder=new MyHolder(v);
return holder;
}
//DATA BOUND TO VIEWS
@Override
public void onBindViewHolder(MyHolder holder, int position) {
//BIND DATA
holder.posTxt.setText(players.get(position).getPos());
holder.nameTxt.setText(players.get(position).getName());
holder.img.setImageResource(players.get(position).getImg());
//IMPLEMENT CLICK LISTENET
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClick(View v, int pos) {
Snackbar.make(v,players.get(pos).getName(),Snackbar.LENGTH_SHORT).show();
}
});
}
//GET TOTAL NUM OF PLAYERS
@Override
public int getItemCount() {
return players.size();
}
//RETURN FILTER OBJ
@Override
public Filter getFilter() {
if(filter==null)
{
filter=new CustomFilter(filterList,this);
}
return filter;
}
}
8. CustomFilter.java
This class will derive from android.widget.Filter
class.
This is the class that will search our data.
package com.tutorials.hp.customrecyclerfiltering;
import android.widget.Filter;
import java.util.ArrayList;
public class CustomFilter extends Filter{
MyAdapter adapter;
ArrayList<Player> filterList;
public CustomFilter(ArrayList<Player> filterList,MyAdapter adapter)
{
this.adapter=adapter;
this.filterList=filterList;
}
//FILTERING OCURS
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
//CHECK CONSTRAINT VALIDITY
if(constraint != null && constraint.length() > 0)
{
//CHANGE TO UPPER
constraint=constraint.toString().toUpperCase();
//STORE OUR FILTERED PLAYERS
ArrayList<Player> filteredPlayers=new ArrayList<>();
for (int i=0;i<filterList.size();i++)
{
//CHECK
if(filterList.get(i).getName().toUpperCase().contains(constraint))
{
//ADD PLAYER TO FILTERED PLAYERS
filteredPlayers.add(filterList.get(i));
}
}
results.count=filteredPlayers.size();
results.values=filteredPlayers;
}else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.players= (ArrayList<Player>) results.values;
//REFRESH
adapter.notifyDataSetChanged();
}
}
9. MainActivity.java
This is our main activity. It derives from android.app.Activity
.
This activity will use the inflated activity_main.xml
as the UI view.
public class MainActivity extends AppCompatActivity {
SearchView sv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
sv= (SearchView) findViewById(R.id.mSearch);
RecyclerView rv= (RecyclerView) findViewById(R.id.myRecycler);
//SET ITS PROPETRIES
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setItemAnimator(new DefaultItemAnimator());
//ADAPTER
final MyAdapter adapter=new MyAdapter(this,getPlayers());
rv.setAdapter(adapter);
//SEARCH
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String query) {
//FILTER AS YOU TYPE
adapter.getFilter().filter(query);
return false;
}
});
}
//ADD PLAYERS TO ARRAYLIST
private ArrayList<Player> getPlayers()
{
ArrayList<Player> players=new ArrayList<>();
Player p=new Player();
p.setName("Ander Herera");
p.setPos("Midfielder");
p.setImg(R.drawable.herera);
players.add(p);
p=new Player();
p.setName("David De Geaa");
p.setPos("Goalkeeper");
p.setImg(R.drawable.degea);
players.add(p);
p=new Player();
p.setName("Michael Carrick");
p.setPos("Midfielder");
p.setImg(R.drawable.carrick);
players.add(p);
p=new Player();
p.setName("Juan Mata");
p.setPos("Playmaker");
p.setImg(R.drawable.mata);
players.add(p);
p=new Player();
p.setName("Diego Costa");
p.setPos("Striker");
p.setImg(R.drawable.costa);
players.add(p);
p=new Player();
p.setName("Oscar");
p.setPos("Playmaker");
p.setImg(R.drawable.oscar);
players.add(p);
return players;
}
}
Download
Resource | Link |
---|---|
GitHub Browse | Browse |
ToolBar SearchBar
There are two ways in which you can achieve a toolbar search. First you can simply place a searchview in your toolbar layout. Then reference the searchview and use it as normal.
Second you can use a variety of searchview libraries like the Material SearchBar Library. We will see this in the next example.
Example 3: Kotlin Android – Search/Filter ListView with SearchView
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.
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:
beforeTextChanged
onTextChanged
– This is where we filter our adapter.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:
Search History
Let’s see how to show search history using a beautiful material searchview library.
Android Material SearchView and History
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.
Build.gradle
First we add the Material SearchView library.
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "com.tutorials.hp.materialsearchgridview"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
compile 'br.com.mauker.materialsearchview:materialsearchview:1.1.0'
}
Second we create a package called br.com.mauker as below and the following class :
package br.com.mauker;
public class MsvAuthority {
public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}
MainActivity.java
Here’s our MainActivity class :
package com.tutorials.hp.materialsearchgridview;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import br.com.mauker.materialsearchview.MaterialSearchView;
public class MainActivity extends AppCompatActivity {
MaterialSearchView msv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
msv= (MaterialSearchView) findViewById(R.id.msv);
msv.addSuggestions(new String[]{"Casini","Andromeda","Europa","Voyager","Spitzer","Hubble"});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
msv.openSearch();
}
});
}
@Override
public void onBackPressed() {
if(msv.isOpen())
{
msv.closeSearch();
}else
{
super.onBackPressed();
}
}
}
activity_main.xml
Then in our layout we add Material searchView as below :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingBottom="@dimen/activity_vertical_margin"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
app_layout_behavior="@string/appbar_scrolling_view_behavior"
tools_context="com.tutorials.hp.materialsearchgridview.MainActivity"
tools_showIn="@layout/activity_main">
<br.com.mauker.materialsearchview.MaterialSearchView
android_id="@+id/msv"
android_layout_width="match_parent"
android_layout_height="match_parent"/>
</RelativeLayout>
For more details and demo,check the video tutorial below : https://www.youtube.com/watch?v=fspKA0xWHxc
Concept 2: Android Material SearchBar Tutorial and Examples