[英]How to make the soft keyboard hide when clicked outside of the focused EditText BUT not if another EditText is clicked?
I want the focused EditText to lose its focus and the soft keyboard to hide when clicked outside the EditText box BUT only when another EditText is not clicked, so these are the scenarios:我希望聚焦的 EditText 失去焦点,并且在 EditText 框外单击时隐藏软键盘,但仅在未单击另一个 EditText 时才隐藏,所以这些是场景:
Right now my implementation looks like this.现在我的实现看起来像这样。
FocusChangeListeners:焦点变化监听器:
edittext1.setOnFocusChangeListener(object : View.OnFocusChangeListener {
override fun onFocusChange(v: View?, hasFocus: Boolean) {
if (!hasFocus) {
edittext1.clearFocus()
}
}
})
edittext2.setOnFocusChangeListener(object : View.OnFocusChangeListener {
override fun onFocusChange(v: View?, hasFocus: Boolean) {
if (!hasFocus) {
edittext2.clearFocus()
}
}
})
DispatchTouchEvent:调度触摸事件:
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
v.clearFocus()
// if not another EditText clicked, hide keyboard
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(v.getWindowToken(), 0)
}
}
}
return super.dispatchTouchEvent(event)
}
The problem I have is that it is only checked if the click was outside of the EditText's box so the soft keyboard is being hidden even if the other EditText is focused with the click.我遇到的问题是,仅在单击位于 EditText 框之外时才检查它,因此即使单击其他 EditText 聚焦,软键盘也会被隐藏。 What is the solution to overcome this issue?
克服这个问题的解决方案是什么?
I was able to come up with an answer based on other implementations found.我能够根据找到的其他实现提出答案。 It's not very elegant but it does the job.
它不是很优雅,但可以完成工作。
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
val x = event.rawX.toInt()
val y = event.rawY.toInt()
if (!outRect.contains(x, y)) {
v.clearFocus()
val et1: EditText? = findViewById(R.id.edittext1)
val et2: EditText? = findViewById(R.id.edittext2)
val rect1 = Rect()
val rect2 = Rect()
val location1 = IntArray(2)
val location2 = IntArray(2)
et1!!.getLocationOnScreen(location1)
rect1.left = location1[0]
rect1.top = location1[1]
rect1.right = location1[0] + et1.width
rect1.bottom = location1[1] + et1.height
et2!!.getLocationOnScreen(location2)
rect2.left = location2[0]
rect2.top = location2[1]
rect2.right = location2[0] + et2.width
rect2.bottom = location2[1] + et2.height
if ((!rect1.contains(x, y)) && (!rect2.contains(x, y))) {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(v.getWindowToken(), 0)
}
}
}
}
return super.dispatchTouchEvent(event)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.