onAttachedToWindow和onDetachedFromWindow的调用时机分析

if (view == null) {

throw new IllegalArgumentException(“view must not be null”);

}

if (display == null) {

throw new IllegalArgumentException(“display must not be null”);

}

if (!(params instanceof WindowManager.LayoutParams)) {

throw new IllegalArgumentException(“Params must be WindowManager.LayoutParams”);

}

final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;

if (parentWindow != null) {

parentWindow.adjustLayoutParamsForSubWindow(wparams);

} else {

// If there’s no parent, then hardware acceleration for this view is

// set from the application’s hardware acceleration setting.

final Context context = view.getContext();

if (context != null

&& (context.getApplicationInfo().flags

& ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {

wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;

}

}

ViewRootImpl root;

View panelParentView = null;

synchronized (mLock) {

// Start watching for system property changes.

if (mSystemPropertyUpdater == null) {

mSystemPropertyUpdater = new Runnable() {

@Override public void run() {

synchronized (mLock) {

for (int i = mRoots.size() - 1; i >= 0; --i) {

mRoots.get(i).loadSystemProperties();

}

}

}

};

SystemProperties.addChangeCallback(mSystemPropertyUpdater);

}

int index = findViewLocked(view, false);

if (index >= 0) {

if (mDyingViews.contains(view)) {

// Don’t wait for MSG_DIE to make it’s way through root’s queue.

mRoots.get(index).doDie();

} else {

throw new IllegalStateException("View " + view

  • " has already been added to the window manager.");

}

// The previous removeView() had not completed executing. Now it has.

}

// If this is a panel window, then find the window it is being

// attached to for future reference.

if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&

wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {

final int count = mViews.size();

for (int i = 0; i < count; i++) {

if (mRoots.get(i).mWindow.asBinder() == wparams.token) {

panelParentView = mViews.get(i);

}

}

}

root = new ViewRootImpl(view.getContext(), display);

view.setLayoutParams(wparams);

mViews.add(view);

mRoots.add(root);

mParams.add(wparams);

}

// do this last because it fires off messages to start doing things

try {

// 这行代码是本文重点关注的!!!

root.setView(view, wparams, panelParentView);

} catch (RuntimeException e) {

// BadTokenException or InvalidDisplayException, clean up.

synchronized (mLock) {

final int index = findViewLocked(view, false);

if (index >= 0) {

removeViewLocked(index, true);

}

}

throw e;

}

}

其中有一句root.setView(view, wparams, panelParentView);,正是这行代码将调用流程转移到了ViewRootImpl.setView()里面,此方法内部最终会触发ViewRootImpl.performTraversals()方法,这个方法就是我们熟悉的View从无到有要经历的3个阶段(measure, layout, draw),不过这个方法内部和我们这里讨论的内容相关的是其1364行代码:host.dispatchAttachedToWindow(mAttachInfo, 0);,这里的host就是Act的DecorView(FrameLayout的子类),我们可以看到是通过这样的dispatch方法将这个调用沿着View tree分发了下去,我们分别看下ViewGroup和View中这个方法的实现,如下:

// ViewGroup中的实现:

void dispatchAttachedToWindow(AttachInfo info, int visibility) {

mGroupFlags |= FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;

// 先调用自己的

super.dispatchAttachedToWindow(info, visibility);

mGroupFlags &= ~FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;

final int count = mChildrenCount;

final View[] children = mChildren;

for (int i = 0; i < count; i++) {

final View child = children[i];

// 递归调用每个child的dispatchAttachedToWindow方法

// 典型的深度优先遍历

child.dispatchAttachedToWindow(info,

combineVisibility(visibility, child.getVisibility()));

}

final int transientCount = mTransientIndices == null ? 0 : mTransientIndices.size();

for (int i = 0; i < transientCount; ++i) {

View view = mTransientViews.get(i);

view.dispatchAttachedToWindow(info,

combineVisibility(visibility, view.getVisibility()));

}

}

// View中的实现:

void dispatchAttachedToWindow(AttachInfo info, int visibility) {

//System.out.println("Attached! " + this);

mAttachInfo = info;

if (mOverlay != null) {

mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);

}

mWindowAttachCount++;

// We will need to evaluate the drawable state at least once.

mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;

if (mFloatingTreeObserver != null) {

info.mTreeObserver.merge(mFloatingTreeObserver);

mFloatingTreeObserver = null;

}

if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {

mAttachInfo.mScrollContainers.add(this);

mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;

}

performCollectViewAttributes(mAttachInfo, visibility);

onAttachedToWindow();

ListenerInfo li = mListenerInfo;

final CopyOnWriteArrayList listeners =

li != null ? li.mOnAttachStateChangeListeners : null;

if (listeners != null && listeners.size() > 0) {

// 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.

for (OnAttachStateChangeListener listener : listeners) {

listener.onViewAttachedToWindow(this);

}

}

int vis = info.mWindowVisibility;

if (vis != GONE) {

onWindowVisibilityChanged(vis);

}

// Send onVisibilityChanged directly instead of dispatchVisibilityChanged.

// As all views in the subtree will already receive dispatchAttachedToWindow

// traversing the subtree again here is not desired.

onVisibilityChanged(this, visibility);

if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {

// If nobody has evaluated the drawable state yet, then do it now.

refreshDrawableState();

}

needGlobalAttributesUpdate(false);

}

从源码我们可以清晰地看到ViewGroup先是调用自己的onAttachedToWindow()方法,再调用其每个child的onAttachedToWindow()方法,这样此方法就在整个view树中遍布开了,注意到visibility并不会对这个方法产生影响。

onDetachedFromWindow的调用过程


和attched对应的,detached的发生是从act的销毁开始的,具体的代码调用流程如下:

ActivityThread.handleDestroyActivity() -->

WindowManager.removeViewImmediate() -->

WindowManagerGlobal.removeViewLocked()方法 —>

ViewRootImpl.die() --> doDie() -->

ViewRootImpl.dispatchDetachedFromWindow()

最终会调用到View层次结构的dispatchDetachedFromWindow方法去,对应的代码如下:

// ViewGroup的:

@Override

void dispatchDetachedFromWindow() {

// If we still have a touch target, we are still in the process of

// dispatching motion events to a child; we need to get rid of that

// child to avoid dispatching events to it after the window is torn

// down. To make sure we keep the child in a consistent state, we

// first send it an ACTION_CANCEL motion event.

cancelAndClearTouchTargets(null);

// Similarly, set ACTION_EXIT to all hover targets and clear them.

exitHoverTargets();

// In case view is detached while transition is running

mLayoutCalledWhileSuppressed = false;

// Tear down our drag tracking

mDragNotifiedChildren = null;

if (mCurrentDrag != null) {

mCurrentDrag.recycle();

mCurrentDrag = null;

}

final int count = mChildrenCount;

final View[] children = mChildren;

for (int i = 0; i < count; i++) {

// 先调用child的方法

children[i].dispatchDetachedFromWindow();

}

clearDisappearingChildren();

final int transientCount = mTransientViews == null ? 0 : mTransientIndices.size();

for (int i = 0; i < transientCount; ++i) {

View view = mTransientViews.get(i);

view.dispatchDetachedFromWindow();

}

// 最后才是自己的

super.dispatchDetachedFromWindow();

}

// View的:

void dispatchDetachedFromWindow() {

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2021最新上万页的大厂面试真题

七大模块学习资料:如NDK模块开发、Android框架体系架构…

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
**第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。
第二,开发几年,不知道如何进阶更进一步,比较迷茫。
第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢!
由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》
点击传送门,即可获取!

读。

2021最新上万页的大厂面试真题

[外链图片转存中…(img-ipnOvSZm-1715680078974)]

七大模块学习资料:如NDK模块开发、Android框架体系架构…

[外链图片转存中…(img-qZxnA0tB-1715680078976)]

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
**第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。
第二,开发几年,不知道如何进阶更进一步,比较迷茫。
第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢!
由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》
点击传送门,即可获取!

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值