-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
  • 12,398
  • 17
  • 59
  • 91

2 Answers2

1

you can use this:

You can make a method and call it on onCreate() method:

public static void hideSoftKeyboard (Activity activity, View view) {
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);}

or simply you can add in manifest file like this:

 <activity android:name="com.your.package.ActivityName"
  android:windowSoftInputMode="stateHidden"  />
Michael Yaworski
  • 12,398
  • 17
  • 59
  • 91
Piyush
  • 23,959
  • 6
  • 36
  • 71
  • I've tried so many solutions **very** similar to this one, so I was even going to try it, but I'm glad I did because it worked perfectly. This is completely general and works no matter what: you don't have to create any specific instances. – Michael Yaworski Aug 24 '13 at 07:09
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
  • 12,398
  • 17
  • 59
  • 91