0

如果我要使用 切换 Activity 的布局setContentView,之前布局的视图会发生什么情况?切换布局时它们会被销毁并再次创建吗?

4

2 回答 2

2

是的,从window的实现可以看到,每次调用setcontentview(),之前的view都被移除了。

@Override
public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();
    } else {
        mContentParent.removeAllViews();
    }
    mLayoutInflater.inflate(layoutResID, mContentParent);
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
}

更深入的内部......您可以看到所有子视图都被删除和取消引用。他们留给GC。

public void removeAllViewsInLayout() {
    final int count = mChildrenCount;
    if (count <= 0) {
        return;
    }

    final View[] children = mChildren;
    mChildrenCount = 0;

    final View focused = mFocused;
    final boolean detach = mAttachInfo != null;
    View clearChildFocus = null;

    needGlobalAttributesUpdate(false);

    for (int i = count - 1; i >= 0; i--) {
        final View view = children[i];

        if (mTransition != null) {
            mTransition.removeChild(this, view);
        }

        if (view == focused) {
            view.clearFocusForRemoval();
            clearChildFocus = view;
        }

        if (view.getAnimation() != null ||
                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
            addDisappearingView(view);
        } else if (detach) {
           view.dispatchDetachedFromWindow();
        }

        onViewRemoved(view);

        view.mParent = null;
        children[i] = null;
    }

    if (clearChildFocus != null) {
        clearChildFocus(clearChildFocus);
    }
}
于 2013-09-05T06:17:42.510 回答
1

是的,所有视图都是从头开始创建的。我不认为,布局中的任何视图都会被回收。

于 2013-09-05T06:12:52.103 回答