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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With