我想使用预定义的共享首选项来设置checkBoxPreference的值,并使用checkBoxPreference设置共享首选项。我尝试了这段代码,但即使我知道“pre_definied_shared_prefs”存在,checkboxPref也总是为空。
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("pre_defined_shared_prefs");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean b = (Boolean) newValue;
Intent i = getIntent();
Integer show_num = i.getIntExtra("show_num", -1);
SettingsManager s = new SettingsManager();
s.setShowNotification(show_num, b, getApplicationContext());
return true;
}
});
为什么会这样,我该如何解决?
答案 0 :(得分:0)
我的偏好标识:
<CheckBoxPreference
android:title="Show Call UI"
android:defaultValue="true"
android:summary="Show Call Interface when clicking call button"
android:key="checkboxPref" />
休息代码:
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());
return true;
}
});
以下是有关如何创建新复选框偏好设置并将其添加到您希望或查看的群组的示例this
public class MyPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.my_preference_activity);
//fetch the item where you wish to insert the CheckBoxPreference, in this case a PreferenceCategory with key "targetCategory"
PreferenceCategory targetCategory = (PreferenceCategory)findPreference("targetCategory");
//create one check box for each setting you need
CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
//make sure each key is unique
checkBoxPreference.setKey("keyName");
checkBoxPreference.setChecked(true);
targetCategory.addPreference(checkBoxPreference);
}
}