为什么我的CheckBoxe的状态从未保存过? [英] Why are my CheckBoxe's state never saved?

查看:62
本文介绍了为什么我的CheckBoxe的状态从未保存过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Fragments 之一中有几个 CheckBox 元素.

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

每次我离开此Fragment时,似乎都不会保存或恢复用户提供的每个碎片的检查状态.

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

FragmentList 示例中,您可以找到:

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"));
        }
}

但是以某种方式 CheckBox 元素不会保存其状态.

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

这是我应该采取的正确方法吗?

Is this the correct approach I should take?

推荐答案

除非您在应用程序的整个生命周期中都保持Fragment引用有效,否则最好将其状态保存在 onSaveInstanceState 中并将其还原到 onActivityCreated 中.

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.

但是,重要的一点还是要通过以下操作在 Activity 级别保存和恢复该状态:

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.

这篇关于为什么我的CheckBoxe的状态从未保存过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆