1 重写Activity dispatchTouchEvent
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (ev.action == MotionEvent.ACTION_DOWN) {
val view = currentFocus
if (view is EditText) {
val out = Rect()
view.getGlobalVisibleRect(out)
"dispatchTouchEvent ${ev.rawX.toInt()} ${ev.y.toInt()} ${!out.contains(ev.rawX.toInt(), ev.y.toInt())}".loge()
if (!out.contains(ev.rawX.toInt(), ev.y.toInt())) {
view.clearFocus()
KeyboardUtils.hideKeyboard(this)
}
}
}
return super.dispatchTouchEvent(ev)
}
2 调用退出软键盘
object KeyboardUtils {
fun hideKeyboard(context: Activity) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// 隐藏软键盘
imm.hideSoftInputFromWindow(context.window.decorView.windowToken, 0)
}
fun showSoftInput(view: View, flags: Int) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
view.isFocusable = true
view.isFocusableInTouchMode = true
view.requestFocus()
imm.showSoftInput(view, flags)
}
}