How to save state in a fragment

I have 4 buttons to replace fragment in activity [fragment A, fragment B, fragment C, fragment D] and then I replace fragment A with activity and change the value in fragment A, after which I replace fragment B with fragment A and replace Fragment C to Fragment B. But I want to replace Fragment A with Fragment C. How to save state in Fragment A.

Code when I commit a fragment

  private void beginFragmentTransaction(BaseFragment fragment) {
    String tag = fragment.getClass().getName();
    currentFragmentTag = tag;

    boolean fragmentPopped = getChildFragmentManager().popBackStackImmediate(tag, 0);

    if (!fragmentPopped) {
        getChildFragmentManager().beginTransaction()
                .replace(R.id.container, fragment, tag)
                .addToBackStack(tag)
                .commit();
    }

}

      

Replacement diagram

fragment A -------> fragment B

fragment B -------> fragment C

fragment C -------> fragment A

PS. I don't want to use the back button to go back to Fragment A, I want to replace Fragment A and restore the data in the first commit.

+3


source to share


1 answer


Instead of restoring state in time, onCreate()

you can choose onRestoreInstanceState()

which the system calls after the method onStart()

. The system onRestoreInstanceState()

only calls if the saved state is saved, so you don't need to check if the value Bundle

is null.

FYI: this is a sample code. Just for your reference.



public class MainFragment extends Fragment {
private String title;
private double rating;
private int year;

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);

savedInstanceState.putString(TITLE, "Gladiator");
savedInstanceState.putDouble(RATING, 8.5);
savedInstanceState.putInt(YEAR, 2000);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

title = savedInstanceState.getString(TITLE);
rating = savedInstanceState.getDouble(RATING);
year = savedInstanceState.getInt(YEAR);
}
}

      

FYI . This is a really good test, also check out How to keep the state of fragment instances on the stack correctly?

+4


source







All Articles