當DecorView
加入到WindowManager
,并且ViewRootImpl
第一次調(diào)用performTraversals
時,會調(diào)用DecorView
的dispatchAttachedToWindow
host.dispatchAttachedToWindow(mAttachInfo, 0);
因為DecorView是ViewGroup,所以會調(diào)用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()));
}
}
除了調(diào)用父類view的dispatchAttachedToWindow,同時還調(diào)用每個child view的dispatchAttachedToWindow
View.dispatchAttachedToWindow
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
mAttachInfo = info;
....
}
View.dispatchAttachedToWindow
將ViewRootImpl
中創(chuàng)建的AttachInfo
傳入View
的mAttachInfo
中,AttachInfo
中有一個變量mTreeObserver
保存了ViewTreeObserver
實例,View
的getViewTreeObserver
方法可以返回這個實例對象
public ViewTreeObserver getViewTreeObserver() {
if (mAttachInfo != null) {
return mAttachInfo.mTreeObserver;
}
if (mFloatingTreeObserver == null) {
mFloatingTreeObserver = new ViewTreeObserver();
}
return mFloatingTreeObserver;
}
ViewTreeObserver的作用就是可以注冊一堆Listener,去監(jiān)聽當前View Hierarchy的各種事件,比如focus change, attach, detach, predraw, draw這些事件。比如:
view.getViewTreeObserver().addOnWindowAttachListener(new ViewTreeObserver.OnWindowAttachListene() {
@Overide
void onWindowAttached() {
}
@Overide
void onWindowDetached() {
}
});
這些事件的調(diào)用是在ViewRootImpl
的performTraversals
中發(fā)送的:
ViewRootImpl.performTraversals
private void performTraversals() {
.....
mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
.....
mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
}
另外整個View Hierarchy的AttachInfo都指向ViewRootImpl中創(chuàng)建的同一個AttachInfo,下一篇文章研究一下這個AttachInfo