Android ViewTreeObserver

DecorView加入到WindowManager,并且ViewRootImpl第一次調用performTraversals時,會調用DecorViewdispatchAttachedToWindow

host.dispatchAttachedToWindow(mAttachInfo, 0);

因為DecorView是ViewGroup,所以會調用ViewGroup的dispatchAttachedToWindow

ViewGroup.dispatchAttachedToWindow

@Override
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    super.dispatchAttachedToWindow(info, visibility);

    final int count = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < count; i++) {
        final View child = children[i];
        child.dispatchAttachedToWindow(info,
                combineVisibility(visibility, child.getVisibility()));
    }
}

除了調用父類view的dispatchAttachedToWindow,同時還調用每個child view的dispatchAttachedToWindow

View.dispatchAttachedToWindow

void dispatchAttachedToWindow(AttachInfo info, int visibility) {
   mAttachInfo = info;
   ....
}

View.dispatchAttachedToWindowViewRootImpl中創建的AttachInfo傳入ViewmAttachInfo中,AttachInfo中有一個變量mTreeObserver保存了ViewTreeObserver實例,ViewgetViewTreeObserver方法可以返回這個實例對象

public ViewTreeObserver getViewTreeObserver() {
    if (mAttachInfo != null) {
        return mAttachInfo.mTreeObserver;
    }
    if (mFloatingTreeObserver == null) {
        mFloatingTreeObserver = new ViewTreeObserver();
    }
    return mFloatingTreeObserver;
}

ViewTreeObserver的作用就是可以注冊一堆Listener,去監聽當前View Hierarchy的各種事件,比如focus change, attach, detach, predraw, draw這些事件。比如:

view.getViewTreeObserver().addOnWindowAttachListener(new ViewTreeObserver.OnWindowAttachListene() {
    @Overide
    void onWindowAttached() {
    }
    @Overide
    void onWindowDetached() {
    }
});

這些事件的調用是在ViewRootImplperformTraversals中發送的:

ViewRootImpl.performTraversals

private void performTraversals() {
  .....
  mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
  
  .....

  mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
}

另外整個View Hierarchy的AttachInfo都指向ViewRootImpl中創建的同一個AttachInfo,下一篇文章研究一下這個AttachInfo

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容