(一)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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章