I currently have a SearchView
in the action bar of my app. When I click the search icon, the SearchView
expands and the keyboard pops up as expecte
I prefer !searchView.isIconified()
over if(isSearchViewVisible)
inside the onBackPressed()
method as option 2 does not work when you have fragments added in your fragmentmanager's
backstack
that you would like to show when the back button is pressed.
My way:
public class CustomSearchView extends SearchView{ public CustomSearchView(final Context context) { super(context); this.setIconifiedByDefault(true); } @Override public boolean dispatchKeyEventPreIme(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { this.onActionViewCollapsed(); } return super.dispatchKeyEventPreIme(event); } }
<item android:id="@+id/menu_search" android:title="@string/menu_search" android:icon="@drawable/ic_search" android:showAsAction="collapseActionView|ifRoom" android:actionViewClass="com.myapp.CustomSearchView"/>
CustomSearchView searchView = (CustomSearchView)menu.findItem(R.id.menu_search).getActionView();
Use
searchView.setIconified(true)
I also used MenuItemCompat.collapseActionView
MenuItemCompat.collapseActionView(menuItem)
If you are not use any function in onBackPressed()
method ,remove it from your Activity.So that the SearchView
itself handle the onBackPress
event.
I am using SearchView as
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchview = (SearchView) MenuItemCompat.getActionView(searchItem);
searchview.setIconifiedByDefault(true);
searchview.setOnQueryTextListener(this);
searchview.setSubmitButtonEnabled(true);
searchview.setQueryHint("Search Here");
super.onCreateOptionsMenu(menu, inflater);
}
and my menu.xml as follows
<item
android:id="@+id/action_search"
android:icon="@drawable/search_tool"
android:orderInCategory="1"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView"/>
Use:
searchView.setIconified(true);
There is a simple way to do this:
@Override
public void onBackPressed() {
if (!searchView.isIconified()) {
searchView.onActionViewCollapsed();
} else {
super.onBackPressed();
}
}
or use:
myToolBar.collapseActionView();
This will make the searchView to collapse before you press the back then the back action will be called.
Both solutions will work.