首先,我知道我可以保留一個片段setRetainInstance(true);
和檢索FragmentManager
當savedInstanceState
。屏幕旋轉保留多個fragmens
但我的情況是,我有三個片段在我的活動,我「交換」使用交易,這取決於用戶的行爲。 我還可以重新創建當前片段,並在onSaveInstanceState(Bundle savedInstanceState)
內保存標記以在用戶旋轉屏幕時恢復它。
我的問題來了,當用戶旋轉屏幕,在一個片段,然後單擊去前一個片段。由於我可以恢復的唯一片段是活動片段,因此我無法在不重新創建片段的情況下向前一個片段展示(丟失了所有的信息)。
這是我的代碼。此外,如果這不是一個好的溶劑,我會apreciate任何提示。
private Fragment1 fragment1;
private Fragment2 fragment2;
private Fragment3 fragment3;
private String currentFragmentTAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight);
...
mFragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
// HOW TO RECOVER ALL FRAGMENTS??
fragment1 = ??;
fragment2 = ??;
fragment3 = ??;
String tag = savedInstanceState.getString(SAVED_FRAGMENT);
Fragment savedFragment = mFragmentManager.findFragmentByTag(tag);
replaceFragment(savedFragment, tag, null);
}
}
// Here, in other funcions, I initialize fragments and show one of them depending of user actions
// I use replaceFragment function to "swap" fragments.
private void replaceFragment(Fragment fragment, String tag, Map<String, Parcelable> objectsToBundle) {
if (fragment != null && !tag.equals(currentFragmentTAG)) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
if (objectsToBundle != null && !objectsToBundle.isEmpty()) {
Bundle bundle = new Bundle();
for (Map.Entry<String, Parcelable> entry : objectsToBundle.entrySet()) {
bundle.putParcelable(entry.getKey(), entry.getValue());
}
fragment.setArguments(bundle);
}
mFragmentTransaction.replace(R.id.fragment_weight_container, fragment, tag);
mFragmentTransaction.commit();
currentFragmentTAG = tag;
}
}
在我的片段我用setRetainInstance(true)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
太謝謝你了!