背景
先说下需求,大意就是点击某个EditText后,系统输入法弹起。此时我们要在键盘上方展示一个视图。为了方便演示,我们这里就在键盘上方弹出一个Toast。
分析
我们可以把事情分为几个步骤:
- 监听到键盘弹起;
- 获取键盘高度H;
- 在高度H处展示视图;
代码
先看效果
先定义一个接口,给键盘弹起事件增加一个接口。
interface IKeyBoardVisibleListener {
fun onSoftKeyBoardVisible(visible: Boolean?, keyboardHeight: Int?)
}
为了方便演示,我们在Activity的onResume方法中直接注册了这个监听。
open class MainActivity: Activity(){
private var mRootView:RelativeLayout?=null
private var mEditText: EditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initViews()
}
private fun initViews() {
mRootView = this.findViewById(R.id.root)
mEditText = findViewById(R.id.editText)
}
override fun onResume() {
super.onResume()
this.addOnSoftKeyBoardVisibleListener(this, object:IKeyBoardVisibleListener{
override fun onSoftKeyBoardVisible(visible: Boolean?, keyboardHeight: Int?) {
var toastText:String = "";
if (keyboardHeight == getStatusBarHeight()) {
toastText = "居底显示"
} else {
toastText = "键盘上方显示"
}
val toast = Toast.makeText(this@MainActivity, toastText, Toast.LENGTH_LONG)
toast.setGravity(Gravity.BOTTOM, 0, keyboardHeight!!)
toast.show()
//Log.d("MyLog","软键盘可见:" + visible + ",键盘高度:" + keyboardHeight)
}
})
}
private fun getStatusBarHeight():Int {
val wm:WindowManager = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val point = Point()
wm.defaultDisplay.getSize(point)
val width = point.x
val height = point.y
var result = 0
val resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
result = this.getResources().getDimensionPixelSize(resourceId)
}
return result;
}
open fun addOnSoftKeyBoardVisibleListener(activity: Activity?, listener: IKeyBoardVisibleListener? ) {
var decorView: View? = activity?.getWindow()?.getDecorView();
decorView?.getViewTreeObserver()?.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
@Override
override fun onGlobalLayout() {
var rect: Rect = Rect();
decorView?.getWindowVisibleDisplayFrame(rect);
//计算出可见屏幕的高度
var displayHight: Int? = rect.bottom - rect.top;
//获得屏幕整体的高度
var hight: Int? = decorView.getHeight();
//获得键盘高度
var keyboardHeight: Int? = hight!! - displayHight!!
//如果新的可见高度小于一定比例了,我们就认为键盘已经弹起
var visible: Boolean? = (displayHight / hight) < 0.8
listener?.onSoftKeyBoardVisible(visible, keyboardHeight)
}
});
}
}
参考
当然,上面的代码很分散。这个方法也并非原创,生产开发可以参考这篇文章的封装。
https://www.jianshu.com/p/9bba256f261f