布局切换视图会发生什么?

时间:2013-09-05 06:10:36

标签: java android android-layout

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

2 个答案:

答案 0 :(得分:2)

是的,从窗口的实现,您可以看到每次调用setcontentview()时,前一个视图都被删除。

@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);
    }
}

答案 1 :(得分:1)

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