您的位置:首页 > 其它

View被键盘挡住时实现动态滚动View

2016-03-21 14:40 176 查看
实例化监听:

OnGlobalLayoutListener 是ViewTreeObserver的内部类,当一个视图树的布局发生改变时,可以被ViewTreeObserver监听到,这是一个注册监听视图树的观察者(observer),在视图树的全局事件改变时得到通知。ViewTreeObserver不能直接实例化,而是通过getViewTreeObserver()获得。

注册监听:

root.getViewTreeObserver().addOnGlobalLayoutListener(loginViewMoveListener);


记得在Activity销毁时,取消观察者:

if (rootView != null){
rootView.getViewTreeObserver().removeGlobalOnLayoutListener(loginViewMoveListener);
}


//监听软键盘弹出之后移动按钮
OnGlobalLayoutListener loginViewMoveListener = new OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
final Rect rect = new Rect();
// 获取root在窗体的可视区域
rootView.getWindowVisibleDisplayFrame(rect);
// 获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)控件高度-控件可见区域最底端高度
int rootInvisibleHeight = rootView.getRootView()
.getHeight() - rect.bottom;

// 若不可视区域高度大于100,则键盘显示
if (rootInvisibleHeight > 100) {
int[] location = new int[2];
// 获取scrollToView在窗体的坐标
// scrollToView.getLocationInWindow(location);
quickItemLayout.getLocationOnScreen(location);
// 计算root滚动高度,使scrollToView在可见区域
int srollHeight = (location[1] + quickItemLayout
.getHeight()) - rect.bottom;
if (recordMoveNum > 0 && srollHeight <= recordMoveNum) {
rootView.scrollTo(0, recordMoveNum);
} else {
recordMoveNum = srollHeight + Util.Dip2Px(getApplicationContext(), 10);
rootView.scrollTo(0, recordMoveNum);
}

} else {
// 键盘隐藏
rootView.scrollTo(0, 0);
}
}
};


知识补充:

两种方式都是,移动的是ViewContent

scrollTo()和scrollBy()都是View的public成员函数,使用这两个函数可以达到同样的目的,只是使用方式不同。

public void scrollBy (int x, int y),将View的Content偏移(x,y)。x控制左右方向的偏移,y控制上下方向的偏移。例如当x>0,y=0时,向右移动x像素,当x<0,y=0时,向左移动x像素,而View的大小和位置不发生改变。如果Content超出了View的范围,则超出的部分会被挡住。

public void scrollTo (int x, int y),将View的Content的位置移动到(x,y),而View的大小和位置不发生改变。如果Content超出了View的范围,则超出的部分会被挡住。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: