据我所知,我在获取时使用与设置时相同的键,但首选项不会保存。我确定我遗漏了一些明显的东西。
我的自定义 DialogPreference 我在其中加载当前首选项并设置新首选项。
public class SemesterDialogPreference extends DialogPreference {
View view;
SharedPreferences settings;
String semester_id_key = this.getContext().getApplicationContext().getString(R.string.pref_semester_id);
DBAdapter db;
@Override
public void onBindDialogView(View view){
this.view = view;
settings = getSharedPreferences();
int curSemesterId = settings.getInt(semester_id_key, 1);
System.out.println("Incoming " + semester_id_key + " equals " + curSemesterId);
// Here I do stuff...
super.onBindDialogView(view);
}
public SemesterDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_set_semester);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
// Do things and set newId
System.out.println("new int for " + semester_id_key + " is " + newId);
Editor editor = getEditor();
editor.putInt(semester_id_key, newId);
editor.commit();
}
}
我的 PreferenceScreen 的 XML
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/pref_header_settings" >
<com.NsouthProductions.gradetrackerpro.SemesterDialogPreference
android:title="@string/pref_title_semester"
android:summary="@string/pref_summary_semester"
android:key="@string/pref_semester_id"
android:dialogMessage="Are you sure?"
android:positiveButtonText="Clear Questss"
android:negativeButtonText="Cancel"/>
</PreferenceCategory>
</PreferenceScreen>
另外,我不明白为什么在线示例不包含getSharedPreferences()
. 我认为这就是android知道要使用哪个文件的方式。