简体   繁体   中英

Android : Save fragment state and restore the view values

Hi iam trying to save the state of the fragment when one fragment is replaced with other fragment. Consider in my Activity i have a fragmentA with textview-1 and textview-2 . when i click on the textview-1 i am replacing fragmentA with fragmentB which has a list view. Now when i click on the fragmentB list item iam getting the list value and updating the textview-1. same thing iam doing for textview-2 but when i return back, the textview-1 value is gone. How to save the state of the fragment A and its textview-1 value.

Tried as below

@Override
public void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
     outState.putString("curChoice", strtext);
}

and in OnActivityCreated()

 if (savedInstanceState != null) {
             // Restore last state for checked position.
             strtext = savedInstanceState.getString("curChoice", "");
             //incrementdata(strtext);
         }

But always the savedInstanceState is giving null.

When any Fragment is destroyed by the system, everything will just happen exactly the same as in an Activity. It means that every single member variables are also destroyed with the fragment. You will have to manually save and restore those variables through the onSaveInstanceState and onActivityCreated methods respectively.

There is no onRestoreInstanceState method inside a Fragment. So you need to do something like as below code.

// These variable are destroyed along with Activity
private String var1,var2;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("VAR1", var1);
    outState.putString("VAR2", var2);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    var1 = savedInstanceState.getInt("VAR1");
    var2 = savedInstanceState.getString("VAR2");
}

Basically every single standard widget such as EditText , TextView , Checkbox and etc. are all already internally implemented those things. You may need to enable it for some View for example you have to set android:freezeText to true for TextView to use the feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM