重寫Activity的dispatchTouchEvent方法
mBottomSend爲底部輸入框佈局
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
event?.let {
if (it.action == MotionEvent.ACTION_DOWN) {
//判斷當前頁面是否已經彈出了軟鍵盤
if (isKeyBoardShowing(context, mBottomSend)) {
var locations = intArrayOf(0, 0)
//計算輸入框距離屏幕左側和頂部的距離
mBottomSend.getLocationInWindow(locations)
val left = locations[0]
val top = locations[1]
val bottom = top + mBottomSend.height //輸入框底部距離屏幕頂部距離
val right = left + mBottomSend.width //輸入框右側距離屏幕左側的距離
val rect = Rect(left, top, right, bottom)
//如果點擊的位置不在輸入框內,則隱藏底部的軟鍵盤
if (!rect.contains(it.x.toInt(), it.y.toInt())) {
hideKeyBoard(context, mBottomSend)
}
}
}
}
return super.dispatchTouchEvent(event)
}
/**
* 隱藏軟鍵盤
*/
fun hideKeyBoard(context: Context, view: View) {
val input = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (input.isActive()) {
input.hideSoftInputFromWindow(view.getWindowToken(), 0)
}
}
/**
* 判斷軟鍵盤是否彈出
*/
fun isKeyBoardShowing(context: Context, v: View): Boolean {
val imm = context.getSystemService(context.INPUT_METHOD_SERVICE) as InputMethodManager
if (imm.hideSoftInputFromWindow(v.getWindowToken(), 0)) {
imm.showSoftInput(v, 0)
return true
//軟鍵盤已彈出
} else {
return false
//軟鍵盤未彈出
}
}