View的Attach状态

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.

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

你可能感兴趣的:(android源码)