How to dismiss keyboard in Android SearchView?

AndroidAndroid ActionbarAndroid 3.0-HoneycombSearchview

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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;
}

Solution 2 - Android

Simple, straight to the point and clean:

  @Override
  public boolean onQueryTextSubmit(String query) {
      // your search methods
      searchView.clearFocus();
      return true;
  }

Solution 3 - Android

just return false on onQueryTextSubmit just like below

@Override
public boolean onQueryTextSubmit(String s) {
     return false;
}

Solution 4 - Android

Somehow it works if you call

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

and then

otherWidget.requestFocus();

Solution 5 - Android

For me, none of the above was working on the first submit. It was hiding and then immediately re-showing the keyboard. I had to post the clearFocus() on the view's handler to make it happen after it was done with everything else.

mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!"".equals(query)) {
                    mSearchView.post(new Runnable() {
                        @Override
                        public void run() {
                            mSearchView.clearFocus();
                        }
                    });
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

Solution 6 - Android

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.

Solution 7 - Android

Edit: I added the better solution on top, but also kept the old answer as a reference.

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

Original Answer: I programmed using a setOnQueryTextListener. When the searchview is hidden the keyboard goes away and then when it is visible again the keyboard does not pop back up.

	//set query change listener
     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
		@Override
		public boolean onQueryTextChange(String newText) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean onQueryTextSubmit(String query) {
			/**
			 * hides and then unhides search tab to make sure keyboard disappears when query is submitted
			 */
				  searchView.setVisibility(View.INVISIBLE);
				  searchView.setVisibility(View.VISIBLE);
			return false;
		}
    	 
     });

Solution 8 - Android

if someone is looking how to collpase searchView/keyboard, use below code

     /*
        setup close button listener
     */
    searchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener {
        adapter.filter(null)//reset default list
        searchView.onActionViewCollapsed() //collapse SearchView/Keyboard
        true
    }

    /*
        setup text change listener
     */
    searchView.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
        override fun onQueryTextSubmit(query: String?): Boolean {
          
            adapter.filter(if(query.isNullOrEmpty()) "" else query)

            searchView.onActionViewCollapsed() //collapse SearchView/Keyboard
            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            adapter.filter(if(newText.isNullOrEmpty()) "" else newText)
            return true
        }
    })

Solution 9 - Android

In a tablet app I'm working on with a dual pane activity, I've wrote only

f.getView().requestFocus(); // f is the target fragment for the search

and that was enough to dismiss the soft keyboard after a search. No need to use InputMethodManager

Solution 10 - Android

I used ActionBarSherlock 4.3 and I have a ProgressDialog. When I dismiss it in postExecute method, Searchview gain focus. To fix that:

//Handle intent and hide soft keyboard
    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
        searchView.setQuery("", false);
        searchView.setIconified(true);
        searchView.clearFocus();
    }

    /*When dismiss ProgressDialog, searchview gain focus again and shows the keyboard. I  call clearFocus() to avoid it.*/

    AsyncTask.onPostExecute(){
      if(pd!=null)
        pd.dismiss();
      if(searchView!=null)
        searchView.clearFocus();
    }

Hope it helps.

Solution 11 - Android

You can use it.

if (isKeybordShowing(MainActivity.this, MainActivity.this.getCurrentFocus())) {
    onBackPressed();
}

public boolean isKeybordShowing(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
        return keyboard.isActive();
    } catch (Exception ex) {
        Log.e("keyboardHide", "cannot hide keyboard", ex);
        return false;
    }
}

Solution 12 - Android

Two solutions that worked for me, the first one using the SearchView instance:

private void hideKeyboard(){
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}

Second solution:

private void hideKeyboard(){
            InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
 }

Solution 13 - Android

Below Code is working for me to hide keyboard in Searchview

MenuItem searchItem = baseMenu.findItem(R.id.menuSearch);

edtSearch= (EditText) searchItem.getActionView().findViewById(R.id.search_src_text);

MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
                        @Override
                        public boolean onMenuItemActionExpand(MenuItem item) {
                            edtSearch.post(new Runnable() {
                                @Override
                                public void run() {
                                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
                                }
                            });
                            return true;
                        }
            
                        @Override
                        public boolean onMenuItemActionCollapse(MenuItem item) {
                            return true;
                        }
                    });

Solution 14 - Android

Why dont you try this? When you touch the X button, you trigger a focus on the searchview no matter what.

ImageView closeButton = (ImageView)searchView.findViewById(R.id.search_close_btn);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = (EditText) findViewById(R.id.search_src_text);
                et.setText("");`enter code here`
                searchView.setQuery("", false);
                searchView.onActionViewCollapsed();
                menuSearch.collapseActionView();
            }
        });

Solution 15 - Android

fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

Solution 16 - Android

 @Override
    public void onResume() {
        super.onResume();
        searchView.clearFocus();
    }

I tried all the answers above but none worked, clearing focus onResume worked for me

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCACuzcatlanView Question on Stackoverflow
Solution 1 - AndroidbkurziusView Answer on Stackoverflow
Solution 2 - AndroiddazitoView Answer on Stackoverflow
Solution 3 - AndroidPlugieView Answer on Stackoverflow
Solution 4 - AndroidRandy Sugianto 'Yuku'View Answer on Stackoverflow
Solution 5 - AndroidTillView Answer on Stackoverflow
Solution 6 - AndroidRidcullyView Answer on Stackoverflow
Solution 7 - AndroidParnitView Answer on Stackoverflow
Solution 8 - AndroidMudassarView Answer on Stackoverflow
Solution 9 - AndroidJose_GDView Answer on Stackoverflow
Solution 10 - AndroidRoger Garzon NietoView Answer on Stackoverflow
Solution 11 - AndroidMert TUTSAKView Answer on Stackoverflow
Solution 12 - AndroidJorgesysView Answer on Stackoverflow
Solution 13 - AndroidAnkita ShahView Answer on Stackoverflow
Solution 14 - AndroidGiancarlo Calderón PeredaView Answer on Stackoverflow
Solution 15 - AndroidnooraldenView Answer on Stackoverflow
Solution 16 - AndroidEldhopjView Answer on Stackoverflow