关于android:View的Attach状态

55次阅读

共计 1861 个字符,预计需要花费 5 分钟才能阅读完成。

View 的 Attach 状态

切入点

addOnAttachStateChangeListener(OnAttachStateChangeListener)

源码剖析

追踪 onViewAttachedToWindow 调用,仅在 dispatchAttachedToWindow 中被调用。

持续追踪 dispatchAttachedToWindowusage

// View#dispatchAttachedToWindow
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    mAttachInfo = info;
    if (mOverlay != null) {
        // 只是散发状态给 Overlay
        mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
    }
    ...
}
// ViewGroup#dispatchAttachedToWindow
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    ...
    for (int i = 0; i < count; i++) {final View child = children[i];
        // 散发状态给子 View
        child.dispatchAttachedToWindow(info,
                combineVisibility(visibility, child.getVisibility()));
    }
    final int transientCount = mTransientIndices == null ? 0 : mTransientIndices.size();
    for (int i = 0; i < transientCount; ++i) {
        // 散发状态给 transient view
        View view = mTransientViews.get(i);
        view.dispatchAttachedToWindow(info,
                combineVisibility(visibility, view.getVisibility()));
    }
}
// ViewGroup#addTransientView
public void addTransientView(View view, int index) {
    ...
    // 散发状态给新增加 transient view
    if (mAttachInfo != null) {view.dispatchAttachedToWindow(mAttachInfo, (mViewFlags & VISIBILITY_MASK));
    }
    ...
}
// ViewGroup#addViewInner
private void addViewInner(View child, int index, LayoutParams params,
            boolean preventRequestLayout) {
    ...
    AttachInfo ai = mAttachInfo;
    if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
        ...
        child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
        ...
    }
    ...
}

后面几处调用,都是散发状态给外部的一些非凡 View,通过addViewInner,咱们能够确认,当View 被增加到视图构造档次时,散发 Attach 状态。

能够用同样的办法验证 onViewDetachedFromWindow,简直是配对的办法,多了一个DisappearingChildren,Framework 外部与transient view 配合用

论断

Attach状态对应 addViewDetach 状态对应 removeViewAttach 翻译为附加,Detach翻译为拆散

相干类

OnAttachStateChangeListener

Interface definition for a callback to be invoked when this view is attached or detached from its window.

当此视图从其窗口附加或拆散时要调用的回调的接口定义。

AttachInfo

A set of information given to a view when it is attached to its parent window.

当视图附加到其父窗口时提供给视图的一组信息。

正文完
 0