我正在尝试保存片段状态。我有一个活动和几个片段。操作顺序:添加第一个片段,手动更改视图(使第一个 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();
}
}