Android 10 编程关闭软键盘失效,求有效解决方案
在Android 10中编程关闭软键盘的解决方案
我之前也碰到过类似的问题——旧的依赖getCurrentFocus()的软键盘隐藏方法在Android 10真机上突然失效,这主要是因为Android 10对窗口焦点管理和输入法交互逻辑做了一些调整,有时候getCurrentFocus()会返回null,导致无法获取有效的窗口Token来触发软键盘隐藏。
下面是几个经过验证、在Android 10上可靠的解决方案:
方案一:使用Activity窗口根View的Token(推荐)
直接获取Activity窗口的DecorView的Token,替代依赖焦点View的Token,这样不管当前界面有没有焦点View,都能准确指向当前Activity的窗口:
public static void hideSoftKeyboard(Activity activity) { if (activity == null) { return; } // 获取Activity窗口的根布局View View decorView = activity.getWindow().getDecorView(); InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager != null) { // 使用DecorView的Token来隐藏软键盘 inputManager.hideSoftInputFromWindow(decorView.getWindowToken(), 0); } }
这个方法相比你原来的代码更稳定,因为它不依赖当前是否有焦点View,适配Android 10的窗口管理逻辑。
方案二:强制设置窗口软键盘模式+双重隐藏
如果方案一还是偶尔失效,可以尝试结合窗口软键盘模式设置,双重调用隐藏方法来确保生效:
public static void forceHideSoftKeyboard(Activity activity) { if (activity == null) { return; } Window window = activity.getWindow(); InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); // 先设置窗口软键盘模式为强制隐藏 window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if (inputManager != null) { // 用DecorView Token隐藏 inputManager.hideSoftInputFromWindow(window.getDecorView().getWindowToken(), 0); // 额外调用hideSoftInputFromInputMethod加固 inputManager.hideSoftInputFromInputMethod(window.getDecorView().getWindowToken(), 0); } }
注意事项
- 确保在合适的生命周期或用户交互时机调用这些方法,比如
onPause()、按钮点击事件中,避免在界面还未完全初始化时调用。 - 如果是在Fragment中使用,可以通过
getActivity()获取当前关联的Activity,再调用上述方法。
内容的提问来源于stack exchange,提问作者WHOATEMYNOODLES
相关产品推荐
相关产品推荐

