Dismiss keyboard when click outside of EditText in android

后端 未结 9 936
旧时难觅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 05:50

    Touch event on a View will start with ACTION_DOWN from being passed from top to this View in view hierachy. Override dispatchTouchEvent to do additional things. Here's an example to extend from FrameLayout in kotlin:

    class TLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet?=null):
            FrameLayout(context, attrs){
    
        var preDispatchTouchEvent: ((ev: MotionEvent?)->Boolean)? = null
    
        override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
            if (preDispatchTouchEvent==null || !preDispatchTouchEvent!!.invoke(ev)) {
                super.dispatchTouchEvent(ev)
            }
            return true
        }
    
    }
    

    Wrap your EditText and other relative Views under this layout, and set preDispatchTouchEvent to dismiss EditText when event is not above it.

    Check this OS question and official doc to have deeper understanding of touch event delivering.

提交回复
热议问题