Question

I have an activity which loads a fragment (say Fragment1) in onCreate. When the user presses a button in Fragment1, I replace Fragment1 with a new fragment, say Fragment2. The problem is that on changing orientation while in Fragment2, the activity is recreated and shows Fragment1 instead of Fragment2. (because I create Fragment1 in onCreate) How can I stick to Fragment2 and also retain its state on orientation change?

Thanks

Was it helpful?

Solution

When a fragment transaction occurs, assign a variable so you know which fragment is being created. Then override OnSavedInstanceState and pass your variable into the bundle.

Then on orientation change, onCreate will be called and you can retrieve your variable from the savedInstanceStateBundle. You can then choose which fragment will be 'loaded' in the onCreate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top