Why are my CheckBoxe's state never saved?

大城市里の小女人 提交于 2021-01-29 07:39:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30014580/why-are-my-checkboxes-state-never-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!