在 Android 开发中,有时需要以编程方式关闭或隐藏软键盘,例如在用户点击特定按钮、切换界面等场景下。然而,Android 对软键盘的处理 API 设计相对复杂,给开发者带来了一定的挑战。
实现步骤
Java 实现
1 2 3 4 5 6
// Check if no view has focus: Viewview=this.getCurrentFocus(); if (view != null) { InputMethodManagerimm= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }
// Only runs if there is a view that is currently focused this.currentFocus?.let { view -> val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager imm?.hideSoftInputFromWindow(view.windowToken, 0) }
静态工具方法(在 Activity 中使用)
1 2 3 4 5 6 7 8 9 10
publicstaticvoidhideKeyboard(Activity activity) { InputMethodManagerimm= (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. Viewview= activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = newView(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }