需求是,某一個下拉欄位可以選擇的值是動態與其他欄位做聯動。
解決辦法:
https://stackoverflow.com/questions/6136770/android-dynamic-array-listpreference
Place preferences.xml in res/xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Some title">
<ListPreference android:key="default_category"
android:title="Dynamic categories" android:summary="Dynamic categories summary"
android:defaultValue="0" />
</PreferenceCategory>
</PreferenceScreen>
In your activity that extends PreferenceActivity you do something like this in onCreate().
ListPreference listPreferenceCategory = (ListPreference) findPreference("default_category");
if (listPreferenceCategory != null) {
ArrayList<Category> categoryList = getCategories();
CharSequence entries[] = new String[categoryList.size()];
CharSequence entryValues[] = new String[categoryList.size()];
int i = 0;
for (Category category : categoryList) {
entries[i] = category.getCategoryName();
entryValues[i] = Integer.toString(i);
i++;
}
listPreferenceCategory.setEntries(entries);
listPreferenceCategory.setEntryValues(entryValues);
}
範例2:
Every XML element in Android can be created programmatically as the element name is also a Java class. Hence you can create a ListPreference in code:
CharSequence[] entries = { "One", "Two", "Three" };
CharSequence[] entryValues = { "1", "2", "3" };
ListPreference lp = new ListPreference(this);
lp.setEntries(entries);
lp.setEntryValues(entryValues);
You could alternatively create it in XML then add the entries/entry values in code:
CharSequence[] entries = { "One", "Two", "Three" };
CharSequence[] entryValues = { "1", "2", "3" };
ListPreference lp = (ListPreference)findPreference("list_key_as_defined_in_xml");
lp.setEntries(entries);
lp.setEntryValues(entryValues);