Is there another way of saving the state of the nested fragment ? Or if we shouldn't do this, why ? Thanks !
02-13 11:42:43.258: E/AndroidRuntime(7167): java.lang.IllegalStateException: Can't retain fragements that are nested in other fragments
02-13 11:42:43.258: E/AndroidRuntime(7167): at android.support.v4.app.Fragment.setRetainInstance(Fragment.java:742)
FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.
You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
LOAD A FRAGMENT: To load a fragment in an activity at first we need to have an activity and xml file which should have a parent layout that may hold the fragment when it is loaded in that layout. For loading a fragment we need to do a fragment transaction that load the fragment in stack.
You can use FragmentManager.saveFragmentInstanceState(Fragment)
to retrieve a fragment state. The return value implements Parcelable, so you can put it in a Bundle.
For restoration, you can provide the state after creating the fragment using Fragment.setInitialSavedState(Fragment.SavedState)
.
Since support library 20+ (https://code.google.com/p/android/issues/detail?id=74222), there is a bug with instance recreation for child Fragments, there is a fix for it - http://ideaventure.blogspot.com.au/2014/10/nested-retained-fragment-lost-state.html
Code from the webpage(add this to your parent Fragment) -
private FragmentManager childFragmentManager() {//!!!Use this instead of getFragmentManager, support library from 20+, has a bug that doesn't retain instance of nested fragments!!!!
if(mRetainedChildFragmentManager == null) {
mRetainedChildFragmentManager = getChildFragmentManager();
}
return mRetainedChildFragmentManager;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (mRetainedChildFragmentManager != null) {
//restore the last retained child fragment manager to the new
//created fragment
try {
Field childFMField = Fragment.class.getDeclaredField("mChildFragmentManager");
childFMField.setAccessible(true);
childFMField.set(this, mRetainedChildFragmentManager);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With