Search code examples
androidandroid-actionbar

Closing Searchview by code (Android : androidx.appcompat.widget)


I have a Searchview in my action bar, for which I would like to have a special behaviour, but I can't achieve. When clicking on search an edit field appears in the action bar. When typing into the search edit field a list of results will be displayed on the fly, when typing.

So far so good, which is the default behaviour.

No I would like to close the searchfield when selecting any result from the list, but currently the searchfield keeps displaying in the action bar.

How can I close the searchfield by code ? (Same behaviour with clicking on the close icon)

Illustration: Actionbar by default:

enter image description here

I click on search and start typing:

enter image description here

I choose first search result "Battle of Uruk":

enter image description here

The appbar still shows the field edit. I have to close the field by clicking on the close button. How can I hide the field by code, so the appbar looks like default first screenshot ?

searchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  
                <close field and show search icon again>
                // my tries, which didn't work correctly
                //searchView.clearFocus();
                //searchView.setIconified(true);
                //searchView.setVisibility(View.GONE);
                //searchItem.setVisible(true);

            }
}

Solution

  • As documantation says : https://developer.android.com/reference/android/widget/SearchView#setIconifiedByDefault(boolean)

     searchView.setQuery("", false);
    
     if (!searchView.isIconifiedByDefault()) {   
         searchView.setIconifiedByDefault(true);
     } 
        
    

    Edit: setIconified(true) and isIconfied() are deprecated

    Also try at menu to set app:showAsAction="always"