4

Hi I am having trouble figuring out how to hide the Android Virtual Keyboard after a search query with a search view. I want the keyboard to disappear when the user presses the return key (ideally when they tap anywhere outside the keyboard but I will settle for the return key for now). I have it working for a query using onQueryTextSubmit working:

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

however I'd like it to also work if the query is an empty string. The problem is onQueryTextSubmit is not fired if it is an empty string: Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string

I'd also not like to use ActionBarSherlock so this solution will not do: Android SearchView empty string

I just want to hide the keyboard after a user searches :( it seems like such a simple problem but is giving me a headache. Any suggestions? Thanks!

Community
  • 1
  • 1
John
  • 250
  • 3
  • 15

4 Answers4

3

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();
Larry McKenzie
  • 3,173
  • 23
  • 22
  • Thanks, but I am looking to know when to implement these (specifically when the search query is empty). – John Jan 07 '14 at 00:16
  • Ok I see what you are trying to do. I will edit my answer. Are you using the compatibility library? If not what version of Android are you targeting? – Larry McKenzie Jan 07 '14 at 00:41
1

Use InputMethodManager:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

for empty query string solution: Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string

Community
  • 1
  • 1
72DFBF5B A0DF5BE9
  • 4,632
  • 2
  • 19
  • 24
  • Thank you but I am not sure if this what I am looking for. As stated above, I have the keyboard hiding on return presses EXCEPT for on empty strings. I already have looked at that link as well as referenced in my original question. – John Jan 06 '14 at 23:49
  • @John, see: http://stackoverflow.com/questions/13527181/searchview-imeoptions-and-onquerytextsubmit-support – 72DFBF5B A0DF5BE9 Jan 06 '14 at 23:50
0

This works:

searchView.setQuery("", false);
searchView.setIconified(true);
Denny Weinberg
  • 2,226
  • 1
  • 16
  • 31
-1

public boolean onQueryTextSubmit(String s) { //Search stuff...

    searchView.setIconified();
    searchView.clearFocus();
    searchView.onActionViewCollapsed();
    return true;
}