In an Android app-
Say I am in an Activity
- MyActivity which holds one Fragment
at a time.
First I loaded Fragment A to it (With no tags I added it to back stack of the FragmentManager
)
Then at some point I loaded Fragment B (Again with no tags I added it to back stack of the FragmentManager
)
Then at some point i loaded Fragment C (Again with no tags I added it to back stack of the FragmentManager
)
I am using popBackStack()
to enable back button behavior so whenever I press back from Fragment C the flow is like:
Fragment C -> Fragment B -> Fragment A -> Close MyActivity..
Everything is perfect :-)
But if I am in Fragment C and the app gets killed in background (I used "do not keep activity flag" from Settings)
and come back online Fragment C is loaded in MyActivity
but the FragmentManager
's back stack contains only Fragment C..
The Back button is messing it up
Fragment C -> Close MyActivity..
Why is it so?
How to properly restore FragmentManager
's back stack within an Activity
?
Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.
As Fragment is embedded inside an Activity, it will be killed when Activity is killed.
when your activity is recreated, the fragment gets destroyed. So you have to create new instance of fragment and add it again. Ok, but you cant retain the fragment view. If you want to retain the data which is in fragment, then use onSaveInstanceState() and onRestoreInstanceState() .
Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .
Try using alwaysRetainTaskState on your root activity. Android automatically clears the Activity backstack because it assumes that it has been a long time since you used the app and that the user wants to start again from the start.
<activity android:alwaysRetainTaskState="true"/>
This setting will prevent that behaviour and it may follow that the behaviour is inherited by the Fragment Manager.
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