Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving UI on orientation change - onSaveInstanceState not working as expected if retaining Fragment

Using compat lib v1 (not using v2|3 because of certain bugs); a variation of this question.

I have a fragment whose UI has various controls whose state I want to maintain on an orientation change.

The parent activity is being destroyed on orientation change (PLEASE don't tell me about manifest changes to avoid activity recreation!!!!).

The fragment calls setRetainInstance(true).

1) Now my understanding is that Views with unique IDs should retain some state on say an orientation change. Given this I would expect a non-null bundle into onCreateView|onActivityCreated but it is null.

2) In any case if I save state in onSaveInstanceState (ensuring I call super) I still get a null bundle in 'onCreateView|onActivityCreated`

3) If I don't call setRetainInstance(true) then I DO get a non-null bundle in onCreateView|onActivityCreated even if I don't have an `onSaveInstanceState' method.

The questions I have is, is this working as expected and my understanding of the life-cycle is broken? Regardless, I'm guessing that the best way forward for me would be to retain the fragment and then maintain the state of the controls myself within the fragment.

Thanks in advance. Peter.

like image 950
PJL Avatar asked Oct 20 '11 12:10

PJL


1 Answers

If you use setRetainInstance(true) then of course the bundle is null. The fragment is not destroyed but only detached from the current activity and attached to the new activity. Only when the fragment is destroyed do you get a bundle with the values you saved in onSaveInstanceState. Just remove setRetainInstance(true) and use the saved values in onCreateView() to setup your custom views.

like image 148
Catalin Morosan Avatar answered Nov 18 '22 15:11

Catalin Morosan