Background:
I have a main Activity
, it wraps a main Fragment
that can be changed, and in order to keep a backstack I use FragmentManager
's backstack.
The main difference from keeping an activity stack is that when a fragment is pushed to the backstack and get replaced it will call it's onDestroyView()
but not it's onDestroy()
, and when it get back it's view will be re-created with onCreateView()
. (however onCreate()
is not called as the fragment object is not disposed)
In an activity stack it won't happen and the views remain.
This has a positive effect on low-end devices as the Android OS can free some memory and you don't have to keep the views right (in my app messages from the server might change the view in any time) so one can save precious bandwidth as well.
The Actual Problem:
Let's say I have a fragment and the user click on something and it's view is changed, e.g. a list is expanded.
If the user then go to another screen (i.e. fragment) the previous fragment will be pushed to the backstack and it's view will be destroyed.
When the user is going back, the fragment will be re-created and will not "remember" the changes the user had made, e.g. the list would not be expanded as it should
so how can I save the state and restore it without making special cases for every view?
Undesired Answers:
- keep the view alive: doing something to keep the view would break the fragment efficiency
- using
onSaveInstanceState()
: it will not get called when the fragment is pushed to the backstack as the activity is not destroyed and that's not a configuration change. - special object: prefer not to do it if there is a way the system can do it for you.
ListView
, button/checkbox state, etc. I believe it will be what you want to do majority of your time. If there's a reason for that, mention that and I hope there are other ways to it. – JennetActivity
state is not much different than that ofFragment
, only difference is that you restore state ofFragment
inonActivityCreated()
. – Jennet