Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.
Sample: (It's shown in Portuguese, but it also works in english and italian).
Before you can use this lib, you have to implement a class named MsvAuthority
inside the br.com.mauker
package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY
. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.
Example:
MsvAuthority.java
package br.com.mauker;
public class MsvAuthority {
public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<application ... >
<provider
android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
android:exported="false"
android:protectionLevel="signature"
android:syncable="true"/>
</application>
</manifest>
To use it, add the dependency:
compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'
And then, on your Activity
layout file, add the following:
<br.com.mauker.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
After that, you'll just need to get the MaterialSearchView
reference by using getViewById()
, and open it up or close it using MaterialSearchView#openSearch()
and MaterialSearchView#closeSearch()
.
P.S.: It's possible to open and close the view not only from the Toolbar
. You can use the openSearch()
method from basically any Button
, such as a Floating Action Button.
// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.openSearch();
}
});
You can also close the view using the back button, doing the following:
@Override
public void onBackPressed() {
if (searchView.isOpen()) {
// Close the search on the back button press.
searchView.closeSearch();
} else {
super.onBackPressed();
}
}
For more information on how to use the lib, check the github page.