0

CONSTRUCTION

Activity A holds Fragment A that is able add Fragment B on backstack.

PROBLEM

Fragment B holds Views generated via API response. State of these Views is what I need to be able to recreate after rotation or when going back to Fragment A by using onBackPressed and lunching Fragment B again.

I've read quite some of the topics on SO about Fragments in backstack and I am aware of their inability to retain instance.

What should I do to achieve such outcome?

JakubW
  • 1,101
  • 1
  • 20
  • 37

1 Answers1

3

Fragments on backstack can always retain instance if you save it. An Activity or a Fragment on a backstack in simply in a paused state. So you want to save the data/variables in the onSaveInstanceState method for that class (you will be overriding it).

Now to restore from the saved state you would have noticed that the onCreate, onCreateView for Activity, Fragment, respectively, have a Bundle savedInstanceState parameter being passed in. This is where you saved your state in the previous step, thus, you can add

if (savedInstanceState != null) { //TODO: restore the state }

to your onCreate/onCreateView method and you should be good to go.

gsb
  • 5,520
  • 8
  • 49
  • 76
mistwalker
  • 781
  • 7
  • 9
  • 1
    This link might help: http://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack – mistwalker Nov 13 '14 at 09:39
  • that link was really helpful, but I still don't know how to retain this layouts. Problem is that some of them are Switches, EditTexts, CheckBox how should I save such data? Most of them are even inside additional containers(LinearLayout). – JakubW Nov 13 '14 at 10:03
  • The way to do it would be to save the state of the data they were showing (eg. Switch is selected or unselected, a LinearLayout / RelativeLayout contains a child view or not and if it does then which one, what is the color currently showing if that is a variable value in your case). You can save this data in your savedInstanceState and then redraw your activity/fragment with that configuration. – mistwalker Nov 13 '14 at 18:19