/**
* 不让软键盘遮住登录按钮
*
* @param main
* @param scroll
*/
public void addLayoutLinstener(final View main, final View scroll) {
main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
main.getWindowVisibleDisplayFrame(rect);
//不可视高度
int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
//说明键盘弹起
if (mainInvisibleHeight > 200) {
int[] location = new int[2];
scroll.getLocationInWindow(location);
int scrollViewHeight = scroll.getHeight();
int location1 = location[1];
int scrollHeight = (location1 + scrollViewHeight + 10) - rect.bottom;
if (scrollHeight > 0) {
main.scrollTo(0, scrollHeight);
}
} else {
main.scrollTo(0, 0);
}
}
});
}
主要思想:实时检测界面的变化,如果键盘弹起,算出滑动的大小;
注意:main是根布局View;scroll是要滑动的空间,也就是登录按钮。location1是scroll的Y轴坐标,scrollViewHeight是scroll控件的高度,rect.bottom是根布局底部到顶部的距离;如果软键盘弹起,必然会挡住scroll控件,挡住多少,我们就需要滑动多少的距离。则滑动的距离计算为:(location1 + scrollViewHeight + 10) - rect.bottom;