Close virtual keyboard on button press

Andrew picture Andrew · Aug 3, 2010 · Viewed 136.1k times · Source

I have an Activity with an EditText, a button and a ListView. The purpose is to type a search screen in the EditText, press the button and have the search results populate this list.

This is all working perfectly, but the virtual keyboard is behaving strange.

If I click the EditText, I get the virtual keyboard. If I click the "Done" button on the virtual keyboard, it goes away. However, if I click my search button before clicking "Done" on the virtual keyboard, the virtual keyboard stays and I can't get rid of it. Clicking the "Done" button does not close the keyboard. It changes the "Done" button from "Done" to an arrow and remains visible.

Thanks for your help

Answer

Paul Maserrat picture Paul Maserrat · Nov 21, 2011
InputMethodManager inputManager = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                     InputMethodManager.HIDE_NOT_ALWAYS);

I put this right after the onClick(View v) event.

You need to import android.view.inputmethod.InputMethodManager;

The keyboard hides when you click the button.