Android中慎用View#getViewTreeObserver#addOnGlobalLayoutListener来获取view的高度

9,912 阅读3分钟

背景

我们经常在view初始化的时候想要获取view的大小,比如在Activity的onCreate方法中想要取得view的大小,有很多小伙伴知道可以在View#getViewTreeObserver#addOnGlobalLayoutListener回调中得到结果,取到结果后,我们一般都会remove掉这个listener,即调用View#getViewTreeObserver#removeOnGlobalLayoutListener或View#getViewTreeObserver#removeGlobalOnLayoutListener两个方法。

先说下原因

View#getViewTreeObserver每次得到的ViewTreeObserver可能不是同一个实例

看几个例子

  • 场景一
package com.lkh.viewtreeobservertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View text = findViewById(R.id.text);
        ViewTreeObserver viewTreeObserver1 = text.getViewTreeObserver();

        Log.i(TAG, "viewTreeObserver1="+viewTreeObserver1 + " text h="+text.getHeight());
        viewTreeObserver1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewTreeObserver viewTreeObserver2 = text.getViewTreeObserver();
//                viewTreeObserver.removeOnGlobalLayoutListener(this);
                Log.i(TAG, "viewTreeObserver2="+ viewTreeObserver2 + " onGlobalLayout text h="+text.getHeight());
            }
        });

    }
}

第一次进入Activity时打印的log:

05-13 13:46:46.737 29528-29528/com.lkh.viewtreeobservertest I/MainActivity: viewTreeObserver1=android.view.ViewTreeObserver@9b3ac41 text h=0
05-13 13:46:46.807 29528-29528/com.lkh.viewtreeobservertest I/MainActivity: viewTreeObserver2=android.view.ViewTreeObserver@370a279 onGlobalLayout text h=57
05-13 13:46:46.827 29528-29528/com.lkh.viewtreeobservertest I/MainActivity: viewTreeObserver2=android.view.ViewTreeObserver@370a279 onGlobalLayout text h=57

我们看到两次获取到的ViewTreeObserver不一样。第一次拿到的是ViewTreeObserver@9b3ac41,在onGlobalLayout回调方法中拿到的是ViewTreeObserver@370a279

  • 场景二
package com.lkh.viewtreeobservertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View text = findViewById(R.id.text);
        ViewTreeObserver viewTreeObserver1 = text.getViewTreeObserver();

        Log.i(TAG, "viewTreeObserver1="+viewTreeObserver1 + " text h="+text.getHeight());
        viewTreeObserver1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewTreeObserver viewTreeObserver2 = text.getViewTreeObserver();
                viewTreeObserver2.removeOnGlobalLayoutListener(this);
                Log.i(TAG, "viewTreeObserver2="+ viewTreeObserver2 + " onGlobalLayout text h="+text.getHeight());
            }
        });

    }
}

第一次进入Activity时打印的log:

05-13 13:50:01.227 29733-29733/com.lkh.viewtreeobservertest I/MainActivity: viewTreeObserver1=android.view.ViewTreeObserver@9b3ac41 text h=0
05-13 13:50:01.277 29733-29733/com.lkh.viewtreeobservertest I/MainActivity: viewTreeObserver2=android.view.ViewTreeObserver@370a279 onGlobalLayout text h=57

跟场景一基本一样,只是在onGlobalLayout中添加了viewTreeObserver2.removeOnGlobalLayoutListener(this),可以看到移除成功了,onGlobalLayout只执行了一次。

  • 场景三
package com.lkh.viewtreeobservertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View text = findViewById(R.id.text);
        final ViewTreeObserver viewTreeObserver1 = text.getViewTreeObserver();

        Log.i(TAG, "viewTreeObserver1="+viewTreeObserver1 + " text h="+text.getHeight());
        viewTreeObserver1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                viewTreeObserver1.removeOnGlobalLayoutListener(this);

                ViewTreeObserver viewTreeObserver2 = text.getViewTreeObserver();
                Log.i(TAG, "viewTreeObserver2="+ viewTreeObserver2 + " onGlobalLayout text h="+text.getHeight());
            }
        });

    }
}

第一次进入Activity时打印的log:

05-13 13:54:02.157 30070-30070/com.lkh.viewtreeobservertest I/MainActivity: viewTreeObserver1=android.view.ViewTreeObserver@9b3ac41 text h=0
05-13 13:54:02.217 30070-30070/com.lkh.viewtreeobservertest E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.lkh.viewtreeobservertest, PID: 30070
    java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again
        at android.view.ViewTreeObserver.checkIsAlive(ViewTreeObserver.java:887)
        at android.view.ViewTreeObserver.removeOnGlobalLayoutListener(ViewTreeObserver.java:599)
        at com.lkh.viewtreeobservertest.MainActivity$1.onGlobalLayout(MainActivity.java:23)
        at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:982)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2462)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1489)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7472)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7224)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

直接removeOnGlobalLayoutListener的时候抛异常了

分析原因

查找原因最好的办法就是直接去看源代码了,我们直接先看View#getViewTreeObserver的源码(android源码看的是sdk28的,每个版本可能有不一样)

View#getViewTreeObserver

public ViewTreeObserver getViewTreeObserver() {
    if (mAttachInfo != null) {
        return mAttachInfo.mTreeObserver;
    }
    if (mFloatingTreeObserver == null) {
        mFloatingTreeObserver = new ViewTreeObserver(mContext);
    }
    return mFloatingTreeObserver;
}
  1. 在上面的三个场景上,Activity#onCreate中,mAttachInfo为null(为什么为null我们以后分析),所以我们在Activity#onCreate中第一次View#getViewTreeObserver拿到的是mFloatingTreeObserver
  2. 在回调方法onGlobalLayout中,mAttachInfo不为null(为什么不为null先不展开说),View#getViewTreeObserver拿到的就是mAttachInfo.mTreeObserver

由上面两条我们知道了为什么场景一中两次拿到的ViewTreeObserver不同的原因。

onGlobalLayout调用的时机

下面我们来看下onGlobalLayout调用的时机。

先在ViewTreeObserver找到调用onGlobalLayout地方,ViewTreeObserver中跟本次分析有关的源码如下

ViewTreeObserver#dispatchOnGlobalLayout


    public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) {
        checkIsAlive();

        if (mOnGlobalLayoutListeners == null) {
            mOnGlobalLayoutListeners = new CopyOnWriteArray<OnGlobalLayoutListener>();
        }

        mOnGlobalLayoutListeners.add(listener);
    }

    public void removeOnGlobalLayoutListener(OnGlobalLayoutListener victim) {
        checkIsAlive();
        if (mOnGlobalLayoutListeners == null) {
            return;
        }
        mOnGlobalLayoutListeners.remove(victim);
    }
    
    private void checkIsAlive() {
        if (!mAlive) {
            throw new IllegalStateException("This ViewTreeObserver is not alive, call "
                    + "getViewTreeObserver() again");
        }
    }
    
    public final void dispatchOnGlobalLayout() {
        // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
        // perform the dispatching. The iterator is a safe guard against listeners that
        // could mutate the list by calling the various add/remove methods. This prevents
        // the array from being modified while we iterate it.
        final CopyOnWriteArray<OnGlobalLayoutListener> listeners = mOnGlobalLayoutListeners;
        if (listeners != null && listeners.size() > 0) {
            CopyOnWriteArray.Access<OnGlobalLayoutListener> access = listeners.start();
            try {
                int count = access.size();
                for (int i = 0; i < count; i++) {
                    //调用方法在这里
                    access.get(i).onGlobalLayout();
                }
            } finally {
                listeners.end();
            }
        }
    }

我们看到调用onGlobalLayout方法的是dispatchOnGlobalLayout方法,再继续找到调用dispatchOnGlobalLayout方法的地方,是在ViewRootImpl#performTraversals方法中调用,如下:

android.view.ViewRootImpl#performTraversals

    private void performTraversals() {
    
        if (mFirst) {
            ...
            host.dispatchAttachedToWindow(mAttachInfo, 0);
            ...
        
        }
        ...
        
        if (...){
            ...
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            ...
        }
        
        ...
    
        if (didLayout) {
            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
            ...
        }
        
        ...
    
        if (triggerGlobalLayoutListener) {
            mAttachInfo.mRecomputeGlobalAttributes = false;
            mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
        }
        
        ...
    }

我们看到这里调用的是mAttachInfo.mTreeObserver里的dispatchOnGlobalLayout,而我们在Activity#onCreate方法中第一次getViewTreeObserver拿到的是mFloatingTreeObserver,并不是mAttachInfo.mTreeObserver,那我们往mFloatingTreeObserver中addOnGlobalLayoutListener怎么会执行回调呢,我们在View源码中查看下使用mFloatingTreeObserver的地方,在View#dispatchAttachedToWindow中找到了它的身影,如下:

View#dispatchAttachedToWindow

   /**
     * @param info the {@link android.view.View.AttachInfo} to associated with
     *        this view
     */
    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
        mAttachInfo = info;

        ...

        if (mFloatingTreeObserver != null) {
            info.mTreeObserver.merge(mFloatingTreeObserver);
            mFloatingTreeObserver = null;
        }

        ...
    }

原来是在这里把它合并到AttachInfo的mTreeObserver中了,看下ViewTreeObserver#merge方法,如下:

ViewTreeObserver#merge

    void merge(ViewTreeObserver observer) {
        
        ...

        if (observer.mOnGlobalLayoutListeners != null) {
            if (mOnGlobalLayoutListeners != null) {
                mOnGlobalLayoutListeners.addAll(observer.mOnGlobalLayoutListeners);
            } else {
                mOnGlobalLayoutListeners = observer.mOnGlobalLayoutListeners;
            }
        }

        ...

        observer.kill();
    }

看到了吧,直接addAll了,全部添加到了AttachInfo的mTreeObserver中。那现在还有个问题,怎么保证合并到AttachInfo的mTreeObserver中的执行时机在mAttachInfo.mTreeObserver.dispatchOnGlobalLayout()执行前,其它我们在上面的源码中已经看到了它们的执行顺序,这里我们再看一下,如下:

android.view.ViewRootImpl#performTraversals

    private void performTraversals() {
    
        if (mFirst) {
            ...
            host.dispatchAttachedToWindow(mAttachInfo, 0);
            ...
        
        }
        ...
        
        if (...){
            ...
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            ...
        }
        
        ...
    
        if (didLayout) {
            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
            ...
        }
        
        ...
    
        if (triggerGlobalLayoutListener) {
            mAttachInfo.mRecomputeGlobalAttributes = false;
            mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
        }
        
        ...
    }

我们看到,顺序依次是dispatchAttachedToWindow、performMeasure、performLayout、dispatchOnGlobalLayout。发现dispatchOnGlobalLayout是在这几个方法的最后面执行,由此可以知道:

  1. 执行dispatchOnGlobalLayout时,已经合并到了AttachInfo的mTreeObserver中
  2. 执行在onGlobalLayout中可以拿到view的宽高,因为performMeasure(测量)、performLayout(布局)已经先执行

再来看下场景三中为什么会抛出异常

先看下log

05-13 13:54:02.217 30070-30070/com.lkh.viewtreeobservertest E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.lkh.viewtreeobservertest, PID: 30070
    java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again
        at android.view.ViewTreeObserver.checkIsAlive(ViewTreeObserver.java:887)
        at android.view.ViewTreeObserver.removeOnGlobalLayoutListener(ViewTreeObserver.java:599)
        at com.lkh.viewtreeobservertest.MainActivity$1.onGlobalLayout(MainActivity.java:23)
        at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:982)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2462)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1489)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7472)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7224)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

回顾代码如下:

final ViewTreeObserver viewTreeObserver1 = text.getViewTreeObserver();

viewTreeObserver1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        viewTreeObserver1.removeOnGlobalLayoutListener(this);

        ViewTreeObserver viewTreeObserver2 = text.getViewTreeObserver();
        Log.i(TAG, "viewTreeObserver2="+ viewTreeObserver2 + " onGlobalLayout text h="+text.getHeight());
    }
});

我们在onGlobalLayout中使用的ViewTreeObserver为第一次获取到的mFloatingTreeObserver,调用removeOnGlobalLayoutListener方法时,会先执行checkIsAlive方法,这里抛异常,mAlive肯定为false。

ViewTreeObserver#removeOnGlobalLayoutListener

    public void removeOnGlobalLayoutListener(OnGlobalLayoutListener victim) {
        checkIsAlive();
        if (mOnGlobalLayoutListeners == null) {
            return;
        }
        mOnGlobalLayoutListeners.remove(victim);
    }
    
    private void checkIsAlive() {
        if (!mAlive) {
            throw new IllegalStateException("This ViewTreeObserver is not alive, call "
                    + "getViewTreeObserver() again");
        }
    }

哪里会把mAlive置为false呢,找到如下代码:

ViewTreeObserver#kill

/**
     * Marks this ViewTreeObserver as not alive. After invoking this method, invoking
     * any other method but {@link #isAlive()} and {@link #kill()} will throw an Exception.
     *
     * @hide
     */
    private void kill() {
        mAlive = false;
    }

而执行kill方法的地方在哪呢,可以看到前面执行merge方法时,就执行了kill方法,再回顾下:

ViewTreeObserver#merge

    void merge(ViewTreeObserver observer) {
        
        ...

        if (observer.mOnGlobalLayoutListeners != null) {
            if (mOnGlobalLayoutListeners != null) {
                mOnGlobalLayoutListeners.addAll(observer.mOnGlobalLayoutListeners);
            } else {
                mOnGlobalLayoutListeners = observer.mOnGlobalLayoutListeners;
            }
        }

        ...

        observer.kill();
    }

看到没,最后执行了kill方法,所以场景三会直接抛异常。 场景二中能remove成功的原因通过上面的分析应该已经很清楚了,就不多说了。

总结

通过上面的代码分析,我们知道:

  1. 每次调用View#getViewTreeObserver得到的实例可能不一样,所以remove的时候不一定能移除。
  2. 直接使用第一次拿到的View#getViewTreeObserver然后保存起来,remove的时候直接用同一个,有可能抛异常。

综上,使用View#getViewTreeObserver的回调方法一定要小心,很有可能出现意想不到的现象,慎用。

扫一扫 关注我的公众号【老罗开发】