How to dismiss keyboard in Android SearchView?

后端 未结 15 1384
萌比男神i
萌比男神i 2020-12-05 06:27

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



        
15条回答
  •  独厮守ぢ
    2020-12-05 06:42

    For me, the following works:

    In my activity I have a member variable

    private SearchView mSearchView;
    

    In onCreateOptionsMenu() I set that variable like so:

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.library, menu);
        mSearchView = (SearchView)menu.findItem(R.id.miSearch).getActionView();
        mSearchView.setOnQueryTextListener(this);
        return true;
    }   
    

    In the QueryTextListener at last, I do this:

    mSearchView.setQuery("", false);
    mSearchView.setIconified(true); 
    

    I had a look at the source code of SearchView, and if you do not reset the query text to an empty string, the SearchView just does that, and does not remove the keyboard neither. Actually, drilling down deep enough in the source code, it comes to the same, yuku suggested, but still I like my solution better, as I do not have to mess around with those low level stuff.

提交回复
热议问题