Java – Hides the keyboard after the user completes a query for the SearchView

Hides the keyboard after the user completes a query for the SearchView… here is a solution to the problem.

Hides the keyboard after the user completes a query for the SearchView

Hello, I can’t figure out how to hide Android virtual keyboard after using Search View for search queries. I want the keyboard to disappear when the user presses the back key (ideally, when they tap anywhere other than the keyboard, but I’ll be content with the back key for now). I made it work for queries that use onQueryTextSubmit:

public boolean onQueryTextSubmit(String s) {
        Search stuff...
        searchView.clearFocus();
        return true;
    }

But I expect it to work fine when the query is empty string. The problem is that onQueryTextSubmit does not fire if it is an empty string: Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string

I also don’t like using ActionBarSherlock, so this solution doesn’t do it: Android SearchView empty string

I just want to hide the keyboard after the user searches 🙁 It may seem like a simple question, but it gives me a headache. Any suggestions?
Thanks!

Solution

If you are using the compatibility library:

MenuItemCompat.collapseActionView(searchItem);//searchItem is an instance of MenuItem

If you are not using the compatibility library:

searchItem.collapseActionView();

Related Problems and Solutions