TomCB TomCB - 3 months ago 17
Android Question

Hide Soft Keyboard from anywhere

Hiding the soft keyboard is pain.
I use some methods based on having an EditText which gets focus, but in my current app the keyboard keeps popping up at some point where a new fragment is loaded.

I have a method in my helper class, but it does not work for me:

//Hide keyboard
public static void hideSoftKeyboard(Activity activity) {
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}


What I would love is a helper method, I could call from anywhere to hide the soft keyboard. Is this possible, or do I always need the find the EditText which is focused?

Answer

Do something like this pass any edittext id of that activity..it will work for that activty

public static void hideSoftKeyboard(Activity activity, EditText editText) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }