隐藏软键盘在 Android 9.0 Pie 中不起作用

Bir*_*ani 3 android android-9.0-pie

我有这段代码用于在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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

除了 Android 9.0 之外,它在其他 Android 版本上运行良好。在Android 9.0中,它没有任何作用,并且软键盘不隐藏。

Bir*_*ani 5

这是因为getCurrentFocus()即使 editText 已获得焦点,也会返回 null。因此没有窗口令牌,没有它我们就无法隐藏键盘。

这是修复方法:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我们从 currentFocused View 获取窗口令牌,android.R.id.content而不是从 currentFocused View 获取它。因此这就像一个魅力。