/**
* 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的可視區(qū)域大小莫鸭,并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);
}
}
});
}
這是一段防止界面被遮擋的代碼详炬,原理是動態(tài)移動被遮擋控件位置