这是我的偏好.xml
<?xml version="1.0" encoding="utf-8"?>
<ListPreference
android:key="KEY_1"
android:title="Title"
android:summary="Summary"
android:dialogTitle="Dialog"
/>
<ListPreference
android:key="KEY_2"
/>
<ListPreference
android:key="KEY_3"
/>
<ListPreference
android:key="KEY_4"
/>
这是Settings.java:
public class Settings extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// some methods to generate entries and values for ListPreference
final List List_1 = // something
final List List_2 = // something
final List List_3 = // something
String[] entry_1 = List_1.toArray(new String[List_1.size()]);
String[] entry_2 = List_2.toArray(new String[List_2.size()]);
String[] entry_3 = List_3.toArray(new String[List_3.size()]);
String[] value_1 = List_1.toArray(new String[List_1.size()]);
String[] value_2 = List_2.toArray(new String[List_2.size()]);
String[] value_3 = List_3.toArray(new String[List_3.size()]);
// set arrays for entries and values
final ListPreference lp1 = (ListPreference)findPreference("KEY_1");
lp1.setEntries(entry_1);
lp1.setEntryValues(value_2);
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setEntries(entry_2);
lp2.setEntryValues(value_1);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setEntries(entry_2);
lp3.setEntryValues(value_2);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setEntries(entry_2);
lp4.setEntryValues(value_3);
// update lp2, lp3, lp4
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String listValue = (String) newValue;
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setDefaultValue(listValue);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setDefaultValue(listValue);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setDefaultValue(listValue);
return true;
}
});
}
}
这对我来说只适用一次。我在这里错过了什么来在lp2,lp3和lp4上进行更新?我想setDefaultValue只创建一次性输入到共享首选项?
答案 0 :(得分:0)
我怀疑您的匿名侦听器是垃圾收集的 - 添加一些调试打印以查看是否调用了侦听器
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("Listener", "I listen");
String listValue = (String) newValue;
// rest is the same
}
});
如果您看不到调试打印,则将您的监听器移动到类字段并且:
public class Settings extends PreferenceActivity {
private OnPreferenceChangeListener mListener=new OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference, Object newValue){
// as before
}
};
// etc - I guess the line below is in onCreate() - correct your formatting !
lp1.setOnPreferenceChangeListener(mListener);
}
}