gpt4 book ai didi

java - Android 复选框通过 SharedPreferences 保存和显示

转载 作者:行者123 更新时间:2023-12-02 05:34:50 24 4
gpt4 key购买 nike

我有这个 Activity ,并且有 2 个复选框,当用户单击其中一个复选框时,它将被检查并保存,但如果我关闭应用程序并重新打开它,则不会保存复选框,这可能是问题所在?没有保存,或者没有加载?

这是我的代码:

package com.myappisawesome;

import com.myappisawesome.R;
import com.pushbots.push.Pushbots;

import android.R.string;
import android.app.Activity;
import android.content.SharedPreferences;

import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class settup extends Activity {
private String SENDER_ID = "ccccc";
private String PUSHBOT_ID = "ccccc";
public static final String PREFS_NAME = "BuyMeCheckBoxes";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notifsettings);
Pushbots.init(this, SENDER_ID , PUSHBOT_ID);
Pushbots.getInstance().setMsgReceiver(GoToApp.class);
Pushbots.getInstance().setRegStatus(true);


final CheckBox auto = (CheckBox) findViewById(R.id.checkBox1);
final CheckBox imobiliare = (CheckBox) findViewById(R.id.checkBox2);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean c1 = settings.getBoolean("auto", false);
boolean c2 = settings.getBoolean("imobiliare", false);

auto.setChecked(c1);
imobiliare.setChecked(c2);




if (auto.isChecked()) {
auto.setChecked(false);
Pushbots.getInstance().tag(getApplicationContext(), "auto", null);

}




if (imobiliare.isChecked()) {
imobiliare.setChecked(false);
Pushbots.getInstance().tag(getApplicationContext(), "imobiliare", null);

}



}




@Override
protected void onStop(){
super.onStop();
final CheckBox auto = (CheckBox) findViewById(R.id.checkBox1);
final CheckBox imobiliare = (CheckBox) findViewById(R.id.checkBox2);

// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();

boolean checkBoxValue1 = auto.isChecked();
boolean checkBoxValue2 = imobiliare.isChecked();

editor.putBoolean("auto", checkBoxValue1);
editor.putBoolean("imobiliare", checkBoxValue2);
editor.commit();;
}


}

最佳答案

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
auto.setChecked(settings.getBoolean("auto", false));
auto.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("auto", auto.isChecked());
editor.commit();;
}
});

在 oncreate 中使用 setOnCheckedChangeListener。并在那里保存您的偏好而不是onstop。在 onstop 中保存您的偏好设置并不是一个好习惯。

关于java - Android 复选框通过 SharedPreferences 保存和显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25087267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com