I am trying to implement my Action Bar by using an Action Bar.
I have two Action Buttons, one of which is a Search Button and the second one is for the Settings.
I have implemented a setting Button, but I can't implement a Search View.
How can I implement that?
Do you have any idea on how I can achieve that?
As the first step you have to prepare search_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"
app:showAsAction="ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
... your others menu items
</menu>
In the next step you have to use this menu in your Fragment
or Activity
and set OnQueryTextListener
for your SearchView
as is shown in the code below:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
If you want to use menu in fragment remember about setHasOptionsMenu(true);
method.
If you want to customise your SearchView
you have to create your own style for this as is shown in the code below:
<style name="CustomAppTheme" parent="Theme.AppCompat">
<item name="searchViewStyle">@style/CustomSearchViewStyle
</item>
</style>
<style name="CustomSearchViewStyle" parent="Widget.AppCompat.SearchView">
<!-- Background for the search query section (e.g. EditText) -->
<item name="queryBackground">...</item>
<!-- Background for the actions section (e.g. voice, submit) -->
<item name="submitBackground">...</item>
<!-- Close button icon -->
<item name="closeIcon">...</item>
<!-- Search button icon -->
<item name="searchIcon">...</item>
<!-- Go/commit button icon -->
<item name="goIcon">...</item>
<!-- Voice search button icon -->
<item name="voiceIcon">...</item>
<!-- Commit icon shown in the query suggestion row -->
<item name="commitIcon">...</item>
<!-- Layout for query suggestion rows -->
<item name="suggestionRowLayout">...</item>
</style>
EXAMPLE To get old style of EditText
in SearchView
<style name="CustomAppTheme" parent="Theme.AppCompat">
<item name="searchViewStyle">@style/CustomSearchViewStyle
</item>
</style>
<style name="CustomSearchViewStyle" parent="Widget.AppCompat.SearchView">
<item name="queryBackground">@android:drawable/editbox_background_normal</item>
</style>
Remember to set this style in AndroidManifest for your Activity:
<activity
android:name=".YourActivity"
android:theme="@style/CustomAppTheme"