说在前面的话
虽然网上的教程已经很多了,但是这里博主还是要写,就当众多教程中的一篇吧~
实现思路
众所周知,在oncreate中View.getWidth和View.getHeight获得的view的高度和宽度为0,这是因为View组件布局要在onResume回调后完成。所以我们这里为rootView(根布局)添加一个OnGlobalLayoutListener监听。查看这个监听器的源码我们可以知道,当view发生改变的时候可以回调。
public interface OnGlobalLayoutListener {
/**
* Callback method to be invoked when the global layout state or the visibility of views
* within the view tree changes
*/
public void onGlobalLayout();
}
这里我们去监听rootView的可见区域,因为当软键盘弹出来之后,rootView的可见区域会发生变化。监听到之后,我们把rootView上移就行了。(rootView.getViewTreeObserver().addOnGlobalLayoutListener)
那么我们怎么去监听可见区域的变化呢?看下面,我们只要在监听器的回调中做处理即可
Rect rect = new Rect();
// 获取root在窗体的可视区域
rootView.getWindowVisibleDisplayFrame(rect);
// 当前视图最外层的高度减去现在所看到的视图的最底部的y坐标
int rootInvisibleHeight = bottomView
.getHeight() - rect.bottom;
// 若rootInvisibleHeight高度大于100,则说明当前视图上移了,说明软键盘弹出了
if (rootInvisibleHeight > 100) {
} else {
// 软键盘没有弹出来的时候
}
这里的bottomView是rootView中最下面的控件,这样我们就监听了软键盘的弹出,可以根据相应的业务逻辑做一些处理~
弹出的处理(这里只做参考,是我的业务逻辑~哈)
我的思路是用View.scrollTo()这种方式把VIEW上移。那么上移多少就需要计算一波了~
//软键盘弹出来的时候
int[] location = new int[2];
// 获取bottomView在窗体的坐标
bottomView.getLocationInWindow(location);
//btnY的初始值为0,一旦赋过一次值就不再变化
if (btnY == 0){
btnY = location[1];
}
// 计算root滚动高度,使scrollToView在可见区域的底部
int srollHeight = (btnY + scroll
.getHeight()) - rect.bottom;
rootView.scrollTo(0, srollHeight);
记得不弹出的时候要还原哦~不然收起软键盘的时候界面没法复原。
rootView.scrollTo(0, 0);