0

I have a few CheckBox elements inside one of my Fragments.

Every time I leave this Fragment it seems to nor save or restore the checked state of each one provided by the user.

In the FragmentList example you can find:

CheckBox check1;
boolean active;
@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("state1", check1.isChecked());
    }

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.
            check1.setChecked(savedInstanceState.getBoolean("state1"));
        }
}

But somehow the CheckBox elements don`t save their state.

Is this the correct approach I should take?

Machado
  • 14,105
  • 13
  • 56
  • 97

1 Answers1

0

Unless you're keeping your Fragment reference alive through the lifecycle of the application, it should be fine to save its state in onSaveInstanceState and restore it in onActivityCreated.

One important point, though, is also to save and restore that state in the Activity level by doing like:

public void onCreate(Bundle savedInstanceState) {
    ...
    if (savedInstanceState != null) {
        // Restore the fragment's instance
        mFragment = getSupportFragmentManager().getFragment(
                savedInstanceState, "fragKey");
        ...
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // Save the fragment's instance
    getSupportFragmentManager().putFragment(outState, "fragKey", mContent);
}

Please check to see how your Activity is behaving in your scenario.

Júlio Zynger
  • 1,168
  • 1
  • 9
  • 12