产品参与测试的结果就是:很多没有写的需求,但是因为体验不好,就变成了bug.
期望 点击输入框外,焦点就不在,光标不闪烁。行吧,做呗。
https://stackoverflow.com/questions/6677969/tap-outside-edittext-to-lose-focus/36411427
Here universal method for all screens. Put it in your activity
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
clearFocusOnOutsideClick()
return super.dispatchTouchEvent(ev)
}
/*
* Clear focus on outside click
* */
private fun clearFocusOnOutsideClick() {
currentFocus?.apply {
if (this is EditText) {
clearFocus()
}
//Hide keyboard
val imm: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
优点是足够省事,对activity中所有的fragment都有效。并且只要有触碰都会收起键盘,滑动页面也可以。
唯一的缺点就是,没有判断 点击的组件是不是自己。所以,点击自己时会先收起键盘再弹出来,点击多个不同的EditText 也会先收起再弹出来。同时也会导致输入框原有的功能:粘贴、选择复制 消失。
产品说,不行。不能选择了。继续改。
判断点击的组件是不是自身(写在activity中):
/**
* 点击输入框外部清除焦点和收起键盘,点击自身不处理
*/
private fun clearFocusOnOutsideClick(event: MotionEvent?) {
currentFocus?.apply {
if (this is EditText) {
if (event == null) {
return@apply
}
val location = intArrayOf(0, 0)
this.getLocationOnScreen(location)
val left = location[0]
val top = location[1]
val right = left + this.measuredWidth
val bottom = top + this.measuredHeight
val x = event.rawX
val y = event.rawY
if (x >= left && x <= right && y >= top && y <= bottom) {
//在点击的是view自己 ,什么也不做
//为了让输入框有正常的功能,比如复制、选择内容
return@apply
}
clearFocus()
//Hide keyboard
KeyboardUtils.hideSoftInput(this)
}
}
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
clearFocusOnOutsideClick(event)
return super.dispatchTouchEvent(event)
}
网友评论