Why isn't my fragments onSaveInstanceState() being called?

前端 未结 2 671
南方客
南方客 2021-01-01 23:05

I have a fragment which has its own state (selected buttons, etc). That state is lost on a screen rotation.

The activity that contains the fragment has a portrait la

相关标签:
2条回答
  • 2021-01-01 23:36

    If the fragment needs a different layout resource when rotated, setRetainInstance(true) cannot be used. This page shows the lifecycle of fragment with setRetainInstance(true).

    Original idea is use onSaveInstanceState() to retain all members data, just like a regular Activity. However, for some reason, onSaveInstanceState() is not get called. But FragmentActivity is correct, as @Eric Kok suggested). The best solution I found is to use Arguments of Fragment.

    See the solution by Fyodor Volchyok, it is simple. Just work as if the outState in onSaveInstanceState(), and savedInstanceState in onViewCreated().

    0 讨论(0)
  • 2021-01-01 23:44

    You can enable myFragment.setRetainInstance(true) to retain the state, but it does this 'automatically', i.e. it retains the values assigned to your class members and does NOT use the onSaveInstanceState (and hence savedInstanceState is always null).

    Make sure the FragmentActivity that hosts this fragment does not override onSaveInstanceState or when it does it should call super.onSaveInstanceState(Bundle).

    0 讨论(0)
提交回复
热议问题