android fragment- How to save states of views in a fragment when another fragment is pushed on top of it
In fragment guide FragmentList example you can find:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
Which you can use later 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);
}
}
I'm a beginner in Fragments but it seems like solution of your problem ;)
OnActivityCreated is invoked after fragment returns from back stack.
How to correctly save instance state of Fragments in back stack?
To correctly save the instance state of Fragment
you should do the following:
1. In the fragment, save instance state by overriding onSaveInstanceState()
and restore in onActivityCreated()
:
class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's state here
}
}
2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState()
and restore in onCreate()
.
class MyActivity extends Activity {
private MyFragment
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}
}
Related Topics
Android: Move a View on Touch Move (Action_Move)
Android View.Getdrawingcache Returns Null, Only Null
How to Change Font Face of Webview in Android
Android Studio Doesn't See Device
Android Push Notifications: Icon Not Displaying in Notification, White Square Shown Instead
Android Starting Service At Boot Time , How to Restart Service Class After Device Reboot
Android Deprecated Apache Module (Httpclient, Httpresponse, etc.)
How to Pass a Variable from Activity to Fragment, and Pass It Back
How to Get an APK File from an Android Device
Difference Between App:Srccompat and Android:Src in Android's Layout Xml
How to Return to a Parent Activity Correctly
Using Alarmmanager to Start a Service at Specific Time
Android Onclicklistener - Identify a Button
Boot_Completed Not Working Android
Android: Remove Left Margin from Actionbar's Custom Layout