0

I want to dismiss the keyboard from the SearchView whenever the user presses the return key on the keyboard.

   country_search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            country_search.clearFocus()
            return true
        }

This code (onQueryTextSubmit) only gets called if something was put into the SearchView and keyboard's enter was pressed. It doesn't work if the SearchView was empty.

How can I dismiss the keyboard when query is empty and the user presses the keyboard enter key?

SmallGrammer
  • 893
  • 9
  • 19
  • Does this answer your question? [Hide Soft keyboard on return key press](https://stackoverflow.com/questions/26645212/hide-soft-keyboard-on-return-key-press) – Nihas Nizar Aug 19 '20 at 16:21

2 Answers2

0

add listener with call back to onSearch

country_search.setOnEditorActionListener { view: TextView, i: Int?, keyEvent: KeyEvent? -> onSearch(view, i, keyEvent) }

Then inside onSearch add below line as per your need

 (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(text.windowToken, 0)
alokHarman
  • 289
  • 1
  • 8
0

The following code works:

In my activity I have a member variable

private SearchView mSearchView;

In onCreateOptionsMenu() I set a variable:

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 did this:

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

I had to 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.

Nihas Nizar
  • 619
  • 8
  • 15