Android 点击EditText失去焦点和隐藏输入框的方法

BaseActivity 加上

  //使editText点击外部时候失去焦点
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
    
    
        if (ev.action == MotionEvent.ACTION_DOWN) {
    
    
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
    
     //点击editText控件外部
                val imm: InputMethodManager =
                    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                if (imm != null) {
    
    
                    assert(v != null)
                    if (v!=null){
    
    
                        hideKeyboard(v)
                    }

                    if (editText != null) {
    
    
                        editText!!.clearFocus()
                    }
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        // 必不可少,否则所有的组件都不会有TouchEvent了
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    var editText: EditText? = null

    fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
    
    
        if (v != null && v is EditText) {
    
    
            editText = v
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }
fun Activity.hideKeyboard(view : View) {
    
    
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0);
}

猜你喜欢

转载自blog.csdn.net/weixin_37077736/article/details/129856766