/**
* 使键盘一直在输入框下方
* @param parentView 根布局
* @param childView 需要显示的最下方View
*/
public void addLayoutListener(final View parentView, final View childView) {
parentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
parentView.getWindowVisibleDisplayFrame(rect);
int mainInvisibleHeight = parentView.getRootView().getHeight() - rect.bottom;
if (mainInvisibleHeight > 100) {
int[] location = new int[2];
childView.getLocationInWindow(location);
int srollHeight = (location[1] + childView.getHeight()) - rect.bottom;
parentView.scrollTo(0, srollHeight);
} else {
parentView.scrollTo(0, 0);
}
}
});
}
二:
/**
*
* @param root 根布局View
* @param scrollToView 需要移动的View
*/
private int firstLocation = 0;
private void controlKeyboardLayout(final View root, final View scrollToView) {
root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect =new Rect();
//获取root在窗体的可视区域
root.getWindowVisibleDisplayFrame(rect);
//获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
int rootInvisibleHeight =root.getRootView().getHeight() - rect.bottom;
//若不可视区域高度大于100,则键盘显示
if (rootInvisibleHeight >100) {
int[] location =new int[2];
//获取scrollToView在窗体的坐标
scrollToView.getLocationInWindow(location);
if (firstLocation < location[1]) {
firstLocation = location[1];
}
LogUtils.e(TAG +" RECT.BOTTOM = " + rect.bottom +" rootInvisibleHeight = " +
rootInvisibleHeight +" location[1] = " + location[1]);
//计算root滚动高度,使scrollToView在可见区域
int srollHeight = (firstLocation +scrollToView.getHeight()) - rect.bottom;
root.scrollTo(0, srollHeight);
}else {//键盘隐藏
root.scrollTo(0, 0);
}
}
});
}