我有这段代码用于在 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);
}
}
}
}
除了 Android 9.0 之外,它在其他 Android 版本上运行良好。在Android 9.0中,没有效果,软键盘不隐藏。
最佳答案
这是因为即使 editText 已获得焦点,getCurrentFocus()
仍返回 null。因此没有窗口 token ,没有它我们就无法隐藏键盘。
修复方法如下:
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);
}
}
}
我们从 android.R.id.content
获取窗口 token ,而不是从 currentFocused View 获取它。因此这就像一个魅力。
关于android - 隐藏软键盘在 Android 9.0 Pie 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104709/