onAttachedToWindow()的调用时机

onAttachedToWindow()在整个Activity生命周期的位置

参考Google上的一张比较详细的Activity生命周期图:
在这里插入图片描述

onAttachedToWindow()调用时机

onAttachedToWindow()方法的调用是在ViewRootImpl的performTraversals()方法:

private void performTraversals() {
	
	...//其他代码
	
	host.dispatchAttachedToWindow(mAttachInfo, 0); //final View host = mView; host就是DecorView,

	...//其他代码

	performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

	...//其他代码
   
    performLayout(lp, mWidth, mHeight);

	...//其他代码

 	performDraw();

 	...//其他代码

}

1.ViewRootImpl.performTraversals() 调用了DecorView.dispatchAttachedToWindow()
2.DecorView没有重写dispatchAttachedToWindow()方法,所以这里会调用父类ViewGroup的dispatchAttachedToWindow()方法
3.ViewGroup的dispatchAttachedToWindow()方法会调用View.onAttachedToWindow()方法
4.DecorView重写了onAttachedToWindow()方法,所以调用DecorView.onAttachedToWindow()
5.DecorView的onAttachedToWindow()方法会获取其所在Window的Window.Callback,而这个Window.Callback就是Window所在的Activity(Activity实现了Window.Callback接口),所以DecorView.onAttachedToWindow() 会回调Activity的onAttachedToWindow() 方法。

// DecorView.java

   @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        final Window.Callback cb = mWindow.getCallback();
        if (cb != null && !mWindow.isDestroyed() && mFeatureId < 0) {
            cb.onAttachedToWindow();
        }

		...//其他代码
		
    }

参考:
onAttachedToWindow()在整个Activity生命周期的位置及使用

https://www.androidos.net.cn/android/9.0.0_r8/xref/frameworks/base/core/java/android/view/ViewRootImpl.java
https://www.androidos.net.cn/android/9.0.0_r8/xref/frameworks/base/core/java/com/android/internal/policy/DecorView.java

发布了535 篇原创文章 · 获赞 94 · 访问量 74万+

猜你喜欢

转载自blog.csdn.net/yzpbright/article/details/105007060
今日推荐