(一)Android ViewTreeObserver的常用技巧

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

A view tree observer is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.... A ViewTreeObserver should never be instantiated by applications as it is provided by the views hierarchy. Refer to View.getViewTreeObserver() for more information.

从上面的描述中,不难看出,ViewTreeObserver是用来帮助我们监听某些View的某些变化的。

在 ViewTreeObserver 中,包含了以下几个接口:

interface ViewTreeObserver.OnGlobalFocusChangeListener当在一个视图树中的焦点状态发生改变时,所要调用的回调函数

interface ViewTreeObserver.OnGlobalLayoutListener当在一个视图树中的布局发生改变时,所要调用的回调函数

interface ViewTreeObserver.OnPreDrawListener(当一个视图树将要绘制时,所要调用的回调函数的接口类

interface ViewTreeObserver.OnScrollChangedListener(当一个视图树中的一些组件发生滚动时,所要调用的回调函数的接口类

interface ViewTreeObserver.OnTouchModeChangeListener(当一个视图树的触摸模式发生改变时,所要调用的回调函数的接口类


(一)使用OnGlobalLayoutListener获取View的真实高度

<span style="font-family:Arial, sans-serif;"> </span><span style="font-family:KaiTi_GB2312;">localView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (localView.getRootView().getHeight() - localView.getHeight() > 100) {
                    int i = AppUtil.dp2Px(mContext, 158.0F);
                    RelativeLayout.LayoutParams localLayoutParams2 = (RelativeLayout.LayoutParams) LoginActivity.this.ll_login_edit_layout.getLayoutParams();
                    localLayoutParams2.setMargins(0, -(i / 2), 0, 0);
                    ll_login_edit_layout.setLayoutParams(localLayoutParams2);
                    ll_login_edit_layout.invalidate();
                    return;
                }
            }
        });</span>

后面几个还没用过



发布了51 篇原创文章 · 获赞 11 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章