Tap outside edittext to lose focus

后端 未结 9 1717
萌比男神i
萌比男神i 2020-12-24 02:02

I just want when click outside the \"edittext\" to automatically lose focus and hide keyboard. At the moment, if I click on the \"edittext\" it focuses but i need to hit the

9条回答
  •  爱一瞬间的悲伤
    2020-12-24 02:36

    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)
        }
    }
    

    kotlin clearfocus android outside

提交回复
热议问题