/**
* rootHeight是window的高
* rectBottom是window的Y坐标
* mainInvisibleHeight是window的Y轴被遮挡的高度
* needScrollHeight是需要滑动的距离(小于0代表下滑,大于0代码上滑)
* 本方法认为输入法的占屏比会超过1/5
*
* @param view layout(可以是当前布局的任意控件或layout)
* @param scroll 要求不被遮挡的控件
*/
private void addLayoutListener(final View view, final View scroll) {
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
//获取window的可视区域大小,并set到rect对象中
view.getWindowVisibleDisplayFrame(rect);
int rootHeight = view.getRootView().getHeight();
int rectBottom = rect.bottom;
int mainInvisibleHeight = rootHeight - rectBottom;
if (mainInvisibleHeight > rootHeight/5) {
int[] location = new int[2];
scroll.getLocationInWindow(location);
int scrollHeight = scroll.getHeight();
int locations = location[1];
int needScrollHeight = (locations + scrollHeight) - rectBottom;
if (needScrollHeight > 0) {
view.scrollTo(0, needScrollHeight);
}
} else {
view.scrollTo(0, 0);
}
}
});
}
这是一段防止界面被遮挡的代码,原理是动态移动被遮挡控件位置
网友评论