I put this on my button listener:
InputMethodManager inputManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
It works perfectly for when the keyboard is up: it closes the keyboard and then continues its execution. The problem is that when no EditText
was ever pressed (none of them are highlighted/focused on), it breaks and the app "stops working".
I guess it would be nice if I could check if an EditText had ever been pressed.
I tried to do this to check:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) // returns true if any view is currently active in the input method
{
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
}
EDIT
I ended up doing this:
I created this method:
public static void hideSoftKeyboard (Activity activity, View view)
{
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
}
I then called the method
in my button listener like this:
hideSoftKeyboard(MainActivity.this, v); // MainActivity is the name of my class and v is the View I used in my button listener method.