AndroidはListPreferenceで実行中にアイテムを追加します
Android の実行時に ListPreference にアイテムを追加するには、次の手順を実行します。
- 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 は、リスト項目とその対応する値を格納する配列リソースです。
- 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>
- 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のキー値に置き換える必要があることに注意してください。