设计原则:与外界充分解耦,绑定对应输入框,外部不需要添加键盘布局,传入activity即可调用。
设计原理:通过传入activity获得其DecorView,添加键盘布局。将键盘布局set到屏幕底部,当输入框获得焦点时,判断输入框所在位置,若键盘弹出会遮挡输入框,则屏幕整体向上滑动一定的距离:
屏幕移动高度为
moveHeight = ( screenHeight - editText.bottom > keyboardHeight ) ? 0 : keyboardHeight + editText.bottom- screenHeight
先上效果:
具体代码:
①获得decorView
findViewById(android.R.id.content));`
②将keyBoardLayout(键盘布局)放到屏幕底部
` FrameLayout.LayoutParams params =new FrameLayout.LayoutParams(FrameLayout
.LayoutParams.MATCH_PARENT,mKeyboardHeight);
params.gravity= Gravity.BOTTOM;
mRootView.addView(keyBoardLayout, params);
`
③显示键盘时,判断decorView是否需要滑动的距离
```Rect rect =new Rect();
mRootView.getWindowVisibleDisplayFrame(rect);
int[] location =new int[2];
mEditText.getLocationOnScreen(location);
int moveHeight = (location[1] +mKeyboardHeight+mEditText.getHeight()) - rect
.bottom;```
若需要滑动
`if(moveHeight >0){
mRootView.getChildAt(0).scrollBy(0,mMoveHeight);
}`
记得隐藏时滑动回去
`mRootView.getChildAt(0).scrollBy(0, -mMoveHeight);`
这样就大功告成啦(撒花 ^_^)~~