请问如何保存状态切换按钮?我有带有加载代码的 MainActivity,它是正确的。这是在 public void onCreate 中。
SharedPreferences editor = getSharedPreferences("mymode", MODE_PRIVATE);
boolean tgpref = editor.getBoolean("tgpref", true); //default is true
if (tgpref == true) { //if (tgpref) may be enough, not sure
chAppStat.setChecked(true);
} else {
chAppStat.setChecked(false);
}
并且在AppInfoAdapter中保存了代码,但是在这个类中是不正确的MODE_PRIVATE。
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
try {
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
如果在 MainActivity 中都是正确的,但如果在两个部分中是不正确的。请给我一些建议或示例。谢谢
最佳答案
您正在读取/保存的键值不同:
读取“tgpref
”
boolean tgpref = editor.getBoolean("tgpref", true); //default is true
并保存“thpref
”
SharedPreferences.Editor editor = getSharedPreferences("mymode",MODE_PRIVATE).edit();
editor.putBoolean("thpref", true); // value to store
editor.commit();
在两者中使用相同的键名“tgpref
”!
更新:
现在您的 AppInfoAdapter 必须实现 OnCheckedChangeListener
public class AppInfoAdapter extends BaseAdapter implements OnCheckedChangeListener{
或将监听器设置为您的复选框:
CheckBox myCheckBox = ( CheckBox ) findViewById( R.id.repeat_checkbox );
myCheckBox .setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
//0 = MODE_PRIVATE
SharedPreferences.Editor editor = getSharedPreferences("mymode", 0).edit();
editor.putBoolean("tgpref", isChecked );
editor.commit();
}
}
});
关于android - Activity 中的共享首选项 - android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183088/