温馨提示×

android在运行时将项添加到ListPreference

小云
101
2023-09-16 04:22:31
栏目: 编程语言

要在Android运行时将项添加到ListPreference中,可以按照以下步骤进行操作:

  1. 在xml布局文件中,添加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是存储列表项和对应值的数组资源。

  1. 在res/values文件夹下的arrays.xml中,添加列表项和对应值的数组资源:
<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>
  1. 在Activity中动态添加列表项到ListPreference中:
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值。

0