要在Android運行時將項添加到ListPreference中,可以按照以下步驟進行操作:
<ListPreference
android:key="key_list_preference"
android:title="List Preference"
android:entries="@array/list_preference_entries"
android:entryValues="@array/list_preference_entry_values"/>
其中@array/list_preference_entries
和@array/list_preference_entry_values
是存儲列表項和對應值的數組資源。
<string-array name="list_preference_entries">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</string-array>
<string-array name="list_preference_entry_values">
<item>value1</item>
<item>value2</item>
<item>value3</item>
</string-array>
ListPreference listPreference = findPreference("key_list_preference");
CharSequence[] newEntries = {"Item 4", "Item 5"};
CharSequence[] newEntryValues = {"value4", "value5"};
CharSequence[] existingEntries = listPreference.getEntries();
CharSequence[] existingEntryValues = listPreference.getEntryValues();
CharSequence[] allEntries = new CharSequence[existingEntries.length + newEntries.length];
CharSequence[] allEntryValues = new CharSequence[existingEntryValues.length + newEntryValues.length];
System.arraycopy(existingEntries, 0, allEntries, 0, existingEntries.length);
System.arraycopy(newEntries, 0, allEntries, existingEntries.length, newEntries.length);
System.arraycopy(existingEntryValues, 0, allEntryValues, 0, existingEntryValues.length);
System.arraycopy(newEntryValues, 0, allEntryValues, existingEntryValues.length, newEntryValues.length);
listPreference.setEntries(allEntries);
listPreference.setEntryValues(allEntryValues);
以上代碼將新的列表項和對應值添加到現有的ListPreference中。要注意的是,"key_list_preference"
應該替換為你在xml布局文件中定義的ListPreference的key值。