Android点击空白区域隐藏键盘

November 12, 2017

重写dispatchTouchEvent拦截点击事件,点击区域不是EditText隐藏键盘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN && shouldHideInput(currentFocus, ev)) {
            hideSoftInput(currentFocus.windowToken)
        }
        return super.dispatchTouchEvent(ev)
    }

    // Check if click on the EditText, return true to hide soft input.
    private fun shouldHideInput(view: View?, event: MotionEvent): Boolean {
        if (view != null && view is EditText) {
            val array = intArrayOf(0, 0)
            view.getLocationInWindow(array)
            val left = array[0]
            val top = array[1]
            val bottom = top + view.getHeight()
            val right = left + view.getWidth()
            return event.x <= left || event.x >= right || event.y <= top || event.y >= bottom
        }
        return false
    }

    // Hide system soft input.
    private fun hideSoftInput(token: IBinder?) {
        token?.let {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}