I'm currently in the process of learning how to convert my app to Material design and I'm a bit stuck right now. I've got the Toolbar added and I have made my navigation drawer overlay all the content.
I'm now trying to create an expandable search that looks like the one in the material guidelines:
This is what I've got right now and I can't figure out how to make it like the above:
This is my menu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
That works, I get a menu item that expands to the SearchView and I can filter my list fine. It doesn't look anything like the 1st picture though.
I tried to use MenuItemCompat.setOnActionExpandListener()
on R.id.action_search
so I could change the home icon to a back arrow, but that doesn't seem to work. Nothing gets fired in the listener. Even if that worked it still wouldn't be very close to the 1st image.
How do I create a SearchView in the new appcompat toolbar that looks like the material guidelines?
It is actually quite easy to do this, if you are using android.support.v7
library.
Declare a menu item
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
Extend AppCompatActivity
and in the onCreateOptionsMenu
setup the SearchView.
import android.support.v7.widget.SearchView;
...
public class YourActivity extends AppCompatActivity {
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
// Retrieve the SearchView and plug it into SearchManager
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
...
}