Android 一个比较完善的软键盘状态监听 KeyBoardWatcher 实现
相信大家都会遇到项目中有EditText控件需要监听输入法软键盘状态的需求
然后你会发现在查找API的时候,并没有这样的监听接口以及靠谱的API
不靠谱的方案:
方案1:
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).isActive
isActive方法是不正确的,看下源码注释 Return true if any view is currently active in the input method. 如果当前view获得焦点则返回true,意思就是说只要edittext获得焦点就返回true,但是你会发现当你关闭输入法的时候edittext还是处于获取焦点状态此方法返回的还是true。
方案2:
return context.window.attributes.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
softInputMode是软键盘的Mode,并不是软键盘的状态status,这是API的理解错误。SOFT_INPUT_STATE_VISIBLE的源码注释读一下就明白了。它的值等同于你在xml里面设置设置android:windowSoftInputMode="stateVisible"这样的属性。SoftInputModeFlags类可以看下
如何曲线救国
使用ViewTreeObserver监听视图变化 如果屏幕高度-视图高度>0 则输入法弹出
这个方案仅适用单屏设备。因为我们知道定制的Android设备是有可能双屏的。输入法如果弹在副屏此方案不适用的。
针对此方案写了工具类。
package com.okay.commonbusiness.utils
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.util.Pair
import android.view.View
import android.view.ViewTreeObserver
/**
*
* @author Liang Jx
*
* @since 2019/8/5 11:36 AM
* @version ${VERSION}
* @desc
*
*/
class KeyBoardWatcher private constructor() {
private var globalLayoutListener: GlobalLayoutListener? = null
private var context: Context? = null
private var decorView: View? = null
interface OnKeyboardStateChangeListener {
/**
* 监听键盘状态变化监听
* @param isShow 是否显示
* @param heightDifference 界面变化的高度差
*/
fun onKeyboardStateChange(isShow: Boolean, heightDifference: Int)
}
/**
* 监听键盘的状态变化
* @param context
* @param decorView
* @param listener
* @return