Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to disable the collapsing of search view on back key pressed android

I have used Sherlock search view widget in action bar for search menu. The code snippet for initializing the search view

        MenuItem item = menu.findItem(R.id.menu_search);
    item.expandActionView();
    mSearchView = (SearchView) item.getActionView();
    mSearchView.setIconifiedByDefault(false);
    mSearchView.setQuery(query, false);
    mSearchView.clearFocus();

The above code shows expanded search view with default search query. The problem is when I press back button the search view again collapses before returning to previous activity in android. I don't want the search view to collapse on back key press. How to prevent search view from collapsing on back key press?

like image 993
user1526671 Avatar asked Apr 24 '13 10:04

user1526671


People also ask

What is collapsingtoolbarlayout in Android?

CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It is designed to be used as a direct child of a AppBarLayout.

How do I use the shortcut to check my Android version?

Use the shortcut the first time you turn on and set up your device or after your device is set up. Learn how to check your Android version. On the side of your device, find both volume keys. Press and hold both volume keys for 3 seconds.

What is the use of back button in Android?

Between all the keys, the back button is used the most in applications for navigating between activities. However, if the navigation stage reaches the start point on the continuous back press, the application shall not immediately close and ask for an input to close in any form like an AlterDialog.


1 Answers

SearchView.setIconifiedByDefault(false) should be enough if you have set the attribute android:showAsAction="always" in your menu xml.

The following snippet works for me:

default_options.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    <item android:id="@+id/action_search"
        android:title="@string/search"
        android:icon="@drawable/topbar_busqueda"
        androidshowAsAction="always"
        android:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

Activity

 @Override
 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     inflater.inflate(R.menu.default_options menu);
     MenuItem menuItem = menu.findItem(R.id.action_search);
     SearchView searchView = (SearchView) menuItem.getActionView();
     prepareSearchViewAdapter(searchView, menuItem);
     super.onCreateOptionsMenu(menu, inflater);
 }

private void prepareSearchViewAdapter(final SearchView searchView, MenuItem menuItem) {
    searchView.setIconifiedByDefault(false);
}
like image 184
Juan José Melero Gómez Avatar answered Nov 15 '22 20:11

Juan José Melero Gómez