Reputation: 5531
Am I missing something or do Fragment
s not have a onRestoreInstanceState()
method? If not, how do I go about attaining something similar?
Upvotes: 133
Views: 82164
Reputation: 1569
onViewStateRestored
of Fragment
is the equivalent of onRestoreInstanceState
of Activity
. But it is called after onActivityCreated(Bundle)
and before onStart()
.
Upvotes: 20
Reputation: 62559
onActivityCreated is deprecated. and i found it just confusing in terms of the fragment lifecycle. just do this:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
// and then:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
savedIInistanceState?.let{
//restore the data here
}
}
Upvotes: 3
Reputation: 3506
I know, that you have accepted answer, but you should read the official documentation about fragments, and it says (paragraph "Handling the Fragment Lifecycle"):
You can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState() callback and restore it during either onCreate(), onCreateView(), or onActivityCreated()
So, you can use that suits you best: onCreate()
, onCreateView()
, or onActivityCreated()
Upvotes: 50
Reputation: 488
In Fragments guide's ListFragment example you can find:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
Which you can use like this:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
}
onActivityCreated()
is invoked after the fragment returns back from the stack.
Upvotes: 30