我有一个复选框首选项,我想从另一个复选框设置它的值。现在我可以从checkboxpreference获取值并将其设置为外部复选框但我不知道如何从该外部复选框设置首选项值。任何帮助请这是我的 代码
getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); musicpref = getPrefs.getBoolean("musicp", true);
CheckBox musiccheck = (CheckBox) findViewById(R.id.checkBox1);
//The external Checkbox, is checked will start service , if not will stop it
musiccheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
Intent musicstart = new Intent(MainActivity.this,
ServiceMusic.class);
startService(musicstart);
} else {
Intent musicstart = new Intent(MainActivity.this,
ServiceMusic.class);
stopService(musicstart);
}
}
});
// Preference checkbox , if is true will set the external checkbox to true
if (musicpref == true) {
musiccheck.setChecked(true);
}else{
musiccheck.setChecked(false);
}
答案 0 :(得分:4)
您可以尝试这样的事情:
SharedPreferences preferendecs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = preferencess.edit();
editor.putBoolean(PREF_NAME, musiccheck.getValue());
editor.commit();
您也可以参考:
http://android-coding.blogspot.in/2011/08/example-of-using-checkboxpreference.html 和
How do I capture changes of a CheckBoxPreference in android development?