How to dismiss keyboard in Android SearchView?

CACuzcatlan picture CACuzcatlan · Sep 14, 2011 · Viewed 48.2k times · Source

I have a searchView in the ActionBar. I want to dismiss the keyboard when the user is done with input. I have the following queryTextListener on the searchView

final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { 
    @Override 
    public boolean onQueryTextChange(String newText) { 
        // Do something 
        return true; 
    } 

    @Override 
    public boolean onQueryTextSubmit(String query) {

        showProgress();
        // Do stuff, make async call

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        return true; 
    } 
};

Based on similar questions, the following code should dismiss the keyboard, but it doesn't work in this case:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

I've also tried:

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

Neither one works. I'm not sure if this is a Honeycomb specific problem or if it's related to the searchView in the ActionBar, or both. Has anyone gotten this working or know why it does not work?

Answer

bkurzius picture bkurzius · Feb 28, 2013

I was trying to do something similar. I needed to launch the SearchActivity from another Activity and have the search term appear on the opened search field when it loaded. I tried all the approaches above but finally (similar to Ridcully's answer above) I set a variable to SearchView in onCreateOptionsMenu() and then in onQueryTextSubmit() called clearFocus() on the SearchView when the user submitted a new search:

private SearchView searchView;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.search_menu, menu);
    searchView = (SearchView) menu.findItem(R.id.menu_search)
            .getActionView(); // set the reference to the searchView
    searchView.setOnQueryTextListener(this); 
    searchMenuItem = (MenuItem) menu.findItem(R.id.menu_search); 
    searchMenuItem.expandActionView(); // expand the search action item automatically
    searchView.setQuery("<put your search term here>", false); // fill in the search term by default
    searchView.clearFocus(); // close the keyboard on load
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    performNewSearch(query);
    searchView.clearFocus();
    return true;
}