使用setRetainInstance时更新的Fragment视图状态丢失(true)

时间:2013-01-17 23:19:32

标签: android view android-fragments state

我正在尝试保存片段状态。我有一个活动和几个片段。操作序列:添加第一个片段,手动更改视图(使第一个LinearLayout GONE和第二个LinearLayout VISIBLE可见),分离片段,添加另一个片段,分离它并再次附加第一个片段。

添加/附加/分离工作正常但setRetainInstanse(true)仅保存初始片段状态。

最后我在我的片段中看到第一个LinearLayout(而不是第二个),所以我试图用手制作但是它不起作用:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(BUNDLE_IS_LOADING)) {
                if (savedInstanceState.getBoolean(BUNDLE_IS_LOADING)) {
                    mBlockContent.setVisibility(View.GONE);
                    mBlockProgress.setVisibility(View.VISIBLE);

                } else {
                    mBlockContent.setVisibility(View.VISIBLE);
                    mBlockProgress.setVisibility(View.GONE);
                }
            }
        }
        }

        setRetainInstance(true);
}

@Override
public void onSaveInstanceState(Bundle b) {
    super.onSaveInstanceState(b);
    b.putBoolean(BUNDLE_IS_LOADING,
            mBlockProgress.getVisibility() == View.VISIBLE);
}

我使用兼容性库rev。 11。

我的解决方案:

    private boolean isProgressing;

private void saveViewsState() {
    isProgressing = mBlockProgress.getVisibility() == View.VISIBLE;
}

private void switchToProgress() {
    mBlockContent.setVisibility(View.GONE);
    mBlockProgress.setVisibility(View.VISIBLE);
}

private void switchToContent() {
    mBlockContent.setVisibility(View.VISIBLE);
    mBlockProgress.setVisibility(View.GONE);
}

@Override
public void onSaveInstanceState(Bundle b) {
    super.onSaveInstanceState(b);
    saveViewsState();
}

@Override
public void onPause() {
    super.onPause();
    saveViewsState();
}

@Override
public void onResume() {
    super.onResume();
    if (isProgressing) {
        switchToProgress();
    } else {
        switchToContent();
    }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (isProgressing) {
        switchToProgress();
    } else {
        switchToContent();
    }
}

0 个答案:

没有答案