背景:我在开发时出现已点击按钮,由于前面焦点了输入框,导致输入法没收回,影响使用体验
想要在Kotlin开发的Android应用中,实现点击输入框外的区域或按钮时,自动收起弹出的软键盘,同时保持输入框本身不消失。
解决方案
我会提供两种最常用且实用的方法,你可以根据场景选择:
方法1:通用工具类(推荐)
创建一个工具类,封装收起软键盘的逻辑,可在任意地方调用(比如按钮点击、点击空白区域时)。
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
/**
* 软键盘工具类
*/
object KeyboardUtils {
/**
* 隐藏软键盘
* @param view 任意View(通常传EditText或当前Activity的根布局)
*/
fun hideSoftKeyboard(view: View) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* 为布局设置点击空白区域隐藏软键盘
* @param rootView 根布局(比如Activity的contentView)
* @param editText 需要监听的输入框
*/
fun setupTouchOutsideToHideKeyboard(rootView: View, editText: EditText) {
rootView.setOnTouchListener { v, event ->
// 判断点击的不是输入框时,隐藏软键盘
if (v != editText) {
hideSoftKeyboard(editText)
}
false
}
}
}方法2:在Activity/Fragment中使用
场景1:点击按钮时收起键盘
// 在Activity的onCreate中
val editText = findViewById<EditText>(R.id.et_input)
val button = findViewById<Button>(R.id.btn_confirm)
// 按钮点击事件
button.setOnClickListener {
// 收起软键盘
KeyboardUtils.hideSoftKeyboard(editText)
// 执行你的按钮逻辑
// ...
}场景2:点击空白区域收起键盘
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val editText = findViewById<EditText>(R.id.et_input)
val rootView = findViewById<View>(android.R.id.content) // 获取Activity根布局
// 设置点击空白区域收起键盘
KeyboardUtils.setupTouchOutsideToHideKeyboard(rootView, editText)
}场景3:更优雅的空白区域监听(处理子View)
如果布局中有多个可点击View,上面的方法可能失效,可使用以下方式:
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (ev.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
if (!outRect.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
// 点击输入框外部,收起键盘
KeyboardUtils.hideSoftKeyboard(v)
// 可选:清除输入框焦点
v.clearFocus()
}
}
}
return super.dispatchTouchEvent(ev)
}关键说明
前置条件:确保你的Activity/Fragment中能正确获取到EditText实例
核心API:InputMethodManager.hideSoftInputFromWindow() 是Android系统提供的隐藏软键盘的核心方法
焦点处理:如果需要同时清除输入框的焦点,可调用 editText.clearFocus()
总结
通用方案:使用封装的KeyboardUtils工具类,可在任意位置调用hideSoftKeyboard()收起键盘
空白区域监听:重写dispatchTouchEvent是最稳定的监听空白区域点击的方式
按钮点击:直接在按钮的点击事件中调用工具类方法即可快速收起键盘
这种实现方式符合Android开发最佳实践,兼容性好,适用于绝大多数场景(包括Activity、Fragment、Dialog等)。
我的APP最终选择方法3,将代码放到需要代码页就可直接使用
版权声明
本文章如果涉及侵权,请联系我。
部分文章系本人原创未经许可,不得转载。



蒙公网安备 15090202000037号
评论列表
发表评论