如何在离开 activity 后保持多个复选框的选中状态?

How to keep the checked state of multiple checkboxes even after leaving the activity?

我真的需要一些帮助。即使搜索了几个小时并阅读了有关 SharedPreferences 的主题,我也无法解决我的问题。

我希望复选框(多个复选框!)保持 checked/unchecked,即使我离开 activity。如果我回到原来的 activity,复选框应该处于与之前相同的状态。 因此,您基本上可以将应用程序置于后台,如果您再次将其置于前台或转到另一个 activity,复选框仍应为 checked/unchecked(取决于用户选中的内容)。

这是我的 Activity.java 代码:

public class TennisActivity extends AppCompatActivity {
    //Variabeln
    CheckBox cb118;
    CheckBox cb119;
    CheckBox cb120;
    CheckBox cb121;
    CheckBox cb122;
    CheckBox cb123;
    CheckBox cb149;
    CheckBox cb150;
    CheckBox cb151;
    CheckBox cb152;
    CheckBox cb153;

    //Going back to menu by pressing back on device
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent homeIntent = new Intent(TennisActivity.this, SportActivity.class);
                startActivity(homeIntent);
                finish();
            }
        }, 1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_tennis);

        //Variabeln initalisiern
        cb118 = (CheckBox) findViewById(R.id.checkBox118);
        cb119 = (CheckBox) findViewById(R.id.checkBox119);
        cb120 = (CheckBox) findViewById(R.id.checkBox120);
        cb121 = (CheckBox) findViewById(R.id.checkBox121);
        cb122 = (CheckBox) findViewById(R.id.checkBox122);
        cb123 = (CheckBox) findViewById(R.id.checkBox123);
        cb149 = (CheckBox) findViewById(R.id.checkBox149);
        cb150 = (CheckBox) findViewById(R.id.checkBox150);
        cb151 = (CheckBox) findViewById(R.id.checkBox151);
        cb152 = (CheckBox) findViewById(R.id.checkBox152);
        cb153 = (CheckBox) findViewById(R.id.checkBox153);
    }
}

提前感谢您的帮助!

使用Shared Preferences 在用户切换复选框时保存当前状态。再次到达 onCreate 后,您可以从中重新加载数据。

获取共享首选项:

SharedPreferences sharedPref = 
getActivity().getSharedPreferences("MY_SHARED_APPLICATIONS_NAME", Context.MODE_PRIVATE);

要写:

SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("MY_BOOL_VARIABLE_KEY", myBoolVariable);
editor.commit();

阅读:

myBoolVariable = sharedPref.getBoolean("MY_BOOL_VARIABLE_KEY", defaultValue);

对于您的特殊情况,您将需要一个密钥来识别每个复选框,如下所示:

private static final String cb118Key = "cb118_key";

然后在初始化复选框后,您应该根据 SharedPreferences 上保存的内容设置它们的状态:

cb118Checked = sharedPref.getBoolean(cb118Key, defaultValue);
cb118.setChecked(cb118Key);

唯一缺少的是在用户更改复选框状态时保存新状态:

cb118.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        editor.putBoolean(cb118Key, isChecked);
        editor.commit();
    }
});

在共享首选项中存储一个标志并检查值。如果为真,则像下面的代码一样设置检查。

String notif = pref.getString("notification", null);
if (notif != null && notif.equalsIgnoreCase("true")){
                checkBoxNotification.setChecked(true);

            }

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (checkBoxn.isChecked()) {
                        notification = "true";
                        editor.putString("notification", notification).commit();

                    } else {
                        notification = "false";
                        editor.putString("notification", notification).commit();
                    }
                }
            });

感谢 Natan,这是解决方案: (请注意,有一些导入 - 通常是自动 - 必须添加,例如 java.util.HashMap)

//Variabeln
CheckBox cb118;
CheckBox cb119;
CheckBox cb120;
CheckBox cb121;
CheckBox cb122;
CheckBox cb123;
CheckBox cb149;
CheckBox cb150;
CheckBox cb151;
CheckBox cb152;
CheckBox cb153;
//TRY
boolean myBoolVariable = false;
private static final String cb118Key = "cb118_key";
private static final String cb119Key = "cb119_key";
private static final String cb120Key = "cb120_key";
private static final String cb121Key = "cb121_key";
private static final String cb122Key = "cb122_key";
private static final String cb123Key = "cb123_key";
private static final String cb149Key = "cb149_key";
private static final String cb150Key = "cb150_key";
private static final String cb151Key = "cb151_key";
private static final String cb152Key = "cb152_key";
private static final String cb153Key = "cb153_key";

SharedPreferences sharedPref = null;


//Zurück zu SportActivity
@Override
public void onBackPressed() {
    //super.onBackPressed();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent homeIntent = new Intent(TennisActivity.this, SportActivity.class);
            startActivity(homeIntent);
            finish();
        }
    }, 1);

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tennis);
    setContentView(R.layout.activity_main);



    //Variabeln initalisiern
    cb118 = (CheckBox) findViewById(R.id.checkBox118);
    cb119 = (CheckBox) findViewById(R.id.checkBox119);
    cb120 = (CheckBox) findViewById(R.id.checkBox120);
    cb121 = (CheckBox) findViewById(R.id.checkBox121);
    cb122 = (CheckBox) findViewById(R.id.checkBox122);
    cb123 = (CheckBox) findViewById(R.id.checkBox123);
    cb149 = (CheckBox) findViewById(R.id.checkBox149);
    cb150 = (CheckBox) findViewById(R.id.checkBox150);
    cb151 = (CheckBox) findViewById(R.id.checkBox151);
    cb152 = (CheckBox) findViewById(R.id.checkBox152);
    cb153 = (CheckBox) findViewById(R.id.checkBox153);

    sharedPref = getSharedPreferences("alessionegrini.checkliste", Context.MODE_PRIVATE);

    // I'll turn that into a map so it's easy to iterate over the values
    Map<String, CheckBox> checkboxMap = new HashMap();
    checkboxMap.put(cb118Key, cb118);
    checkboxMap.put(cb119Key, cb119);
    checkboxMap.put(cb120Key, cb120);
    checkboxMap.put(cb121Key, cb121);
    checkboxMap.put(cb122Key, cb122);
    checkboxMap.put(cb123Key, cb123);
    checkboxMap.put(cb149Key, cb149);
    checkboxMap.put(cb150Key, cb150);
    checkboxMap.put(cb151Key, cb151);
    checkboxMap.put(cb152Key, cb152);
    checkboxMap.put(cb153Key, cb153);

    loadInitialValues(checkboxMap);
    setupCheckedChangeListener(checkboxMap);
}

public void loadInitialValues(Map<String, CheckBox> checkboxMap) {
    for (Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
        Boolean checked = sharedPref.getBoolean(checkboxEntry.getKey(), false);
        checkboxEntry.getValue().setChecked(checked);
    }
}

public void setupCheckedChangeListener(Map<String, CheckBox> checkboxMap) {
    for (final Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
        checkboxEntry.getValue().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                final SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean(checkboxEntry.getKey(), isChecked);
                editor.apply();
            }
        });
    }
}}