0

I have two fragments, FragmentA and FragmentB, the user can go from FragmentA to FragmentB

Let's say FragmentA has a local variable varA. When the user is on FragmentA and changes orientation I can save that variable with onSaveInstanceState and then restore it in onViewCreated. No problem there.

However, when the user is on FragmentB and the orientation changes, onSaveInstanceState is called for FragmentA, but onViewCreated is never called and the variable is never restored.

How can I restore the variable properly?

Eratia
  • 1
  • Not really an answer to your question, but your best choice is usually to have such variables live elsewhere if you want them to persist longer. The owning activity ViewModel is often a good choice. Have a look [here](https://stackoverflow.com/questions/70855873/create-a-shared-viewmodel-with-factory/70857608#70857608) for an example. – Tyler V May 18 '22 at 00:56
  • I was able to do what I wanted using ViewModel as you said, and the code feels cleaner. Thank you! I'm still curious if the way I wanted to do it originally was possible though – Eratia May 18 '22 at 01:41
  • No problem - it's always so much cleaner to have all the state live in the ViewModel and have the activities and fragments just observe the data. I don't know if your original way was possible or not - `onViewCreated` would eventually be called for `FragmentA` when it is displayed, but if you need access to it before it gets displayed that may not be possible. – Tyler V May 18 '22 at 01:56

0 Answers0