JakubW
JakubW

Reputation: 1121

Fragment and Fragment on BackStack

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?

Upvotes: 0

Views: 156

Answers (1)

mistwalker
mistwalker

Reputation: 781

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.

Upvotes: 3

Related Questions