I have a couple of fragments which substitute one for another. The UI of these fragments changes and I need to hold it's new state. So the code looks pretty trivial:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
if (mStepTwo == null) {
mStepTwo = new QuizStepTwo();
mStepTwo.setListener(mStepTwoListener);
} else {
fragmentTransaction.remove(mStepTwo);
}
fragmentTransaction.replace(R.id.step_holder, mStepTwo);
fragmentTransaction.addToBackStack("second_step");
fragmentTransaction.commit();
However when I replace the second step with the first, for instance by pressing the back-button,- its' UI state rolls back to initial.
How do I hold the state ? OnSaveInstanceState ? or something more comfortable ?
Similar questions: Android Fragment view state within a tab host, How to restore Android fragment view state
A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.
The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is detached from its host activity. The fragment is no longer active and can no longer be retrieved using findFragmentById() . onDetach() is always called after any Lifecycle state changes.
These files contain only the onCreateView() method to inflate the UI of the fragment and returns the root of the fragment layout. If the fragment does not have any UI, it will return null.
Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.
I haven't used this, so mileage may vary. You could try using the FragmentManager.saveFragmentInstanceState
method when replacing Fragments, then use Fragment.setInitialSavedState
method when restoring the Fragment. From the docs, it sounds like it may only work if making a new Fragment of the same type, so unsure if this will work with your current implementation.
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