Restore fragment's previous state on rotation and position in backstack

446 Views Asked by At

I have an app with a single activity showing a fragment to the user. On a click on a button, the activity shows another fragment but keeping the previous one in the backstack. I have now two problems:

  • On rotation (particularly in the second fragment), the data entered in the EditTexts is cleared
  • I want the backstack to be also restored with the text previously entered in the second fragment.

The problem is that when I save data to bundle using OnSaveInstanceState(...), I successfully get it again from OnViewCreated(...) but when I use editText.setText(str), the text is not shown.

At the moment, I think this is because the fragment is then destroyed and recreated by the parent Activity.

How can I do to make it work properly?

Thanks.

1

There are 1 best solutions below

3
Tobias Alt On

Make your fragments retainable:

setRetainInstance(true);

See the following guideline on orientation change state android orientation changes `