Create xml list preference entry names from xml array item names

121 views Asked by At

I define a list preference in xml by using the arrays letter_names and letter_values. They look like:

<string-array name="letter_names">
<item name="a">"a"</item>
<item name="b">"b"</item>
<item name="c">"c"</item>
</string-array>

and

<array name="letter_values">
<item name="a">1</item>
<item name="b">2</item>
<item name="c">3</item>
</array>

The the list is defined in a separate file and loaded by my preferences fragment.

<ListPreference
    android:key="list_preference"
    android:title="Select letter"
    android:summary="This is the letters"
    android:entries="@array/letter_names"
    android:entryValues="@array/letter_values"
    android:dialogTitle="Letters"
    />

This works but seems a bit unnecessarily redundant and irrational to me. I would like to define the values of android:entries by using the name of the <items> in the array letter_values. This way I can use only one array and match entries and values easily.

Can I do this in the xml and if so how?

To do it programatically when loading the preference is not the option I'm looking for.

1

There are 1 answers

1
quinnjn On

I don't think it is possible to combine entries and entryValues into one via the XML resource. My reasoning is from Chet Haase's Developing for Android series.

Avoid arrays of objects: If you have an array of simple plain old data objects, consider one array for each field. For example, assume you have a drawing application which needs to keep track of a list of previous touch X/Y point data. Instead of storing a Point[] array, consider instead storing two int[] arrays, one for X and one for Y. This not only reduces raw object count (and thus memory overhead), but also increases data locality and makes better use of precious memory bandwidth and CPU cache space.

Two primitive arrays are preferred over an array of objects. If the Android engineer's had this in mind when building this, they wouldn't have built in a way to combine entries and entryValues.