Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding SoftKeyboard not working in Android 9.0 Pie

I had this code for hiding soft keyboard in android:

public void hideKeyboard() {
    if (getActivity() != null) {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }
}

It is working fine for other Android version except Android 9.0. In Android 9.0, it has no effect and soft keyboard is not hiding.

like image 748
Birju Vachhani Avatar asked Nov 23 '25 12:11

Birju Vachhani


1 Answers

This is because getCurrentFocus() is returning null even though editText had focused. Hence no window token and we cannot hide keyboard without it.

Here is the fix:

public void hideKeyboard() {
    if (getActivity() != null) {
        InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (manager != null) {
            manager.hideSoftInputFromWindow(getActivity().findViewById(android.R.id.content).getWindowToken(), 0);
        }
    }
}

we are getting window token from android.R.id.content rather than getting it from currentFocused View. hence this works like a charm.

like image 125
Birju Vachhani Avatar answered Nov 25 '25 03:11

Birju Vachhani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!