-3

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.
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97

1 Answers1

0

Mediocre/bad solution, because it doesn't work as general as I want it to:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

EditText x = (EditText)findViewById(R.id.editText);
x.requestFocus(); // this way no matter what, an EditText is focused on.

imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97