Dismiss keyboard when click outside of EditText in android

后端 未结 9 937
旧时难觅i
旧时难觅i 2021-02-01 05:31

I have an EditText called myTextview. I want the soft keyboard to show when I click on the EditText but then dismiss if I click outside of

9条回答
  •  佛祖请我去吃肉
    2021-02-01 06:04

    I use below Process. It's Working For Me Perfectly. Add below function in your activity Class.

      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())) {
                    Log.d("focus", "touchevent")
                    v.clearFocus()
                    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v.windowToken, 0)
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }
    

    Then I will Check Focus status in my fragment.

    appCompatEditText.onFocusChangeListener = View.OnFocusChangeListener { view, hasFocus ->
                    if (!hasFocus) {
                        toast("Focus Off")
                    }else {
                        toast("Focus On")
                    }
                }
    

    I was Checked in Fragment. I needed Focus status for my task Requirement. Focus Out I needed some task.

提交回复
热议问题