如何从Java端为ListPreference创建动态数组。
我不要使用Xml以下。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
<item>Value 1</item>
<item>Value 2</item>
<item>Value 3</item>
</string-array>
<string-array name="listValues">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
</resources>
答案 0 :(得分:22)
将preferences.xml放在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>
在扩展PreferenceActivity的活动中,您可以在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);
}