Jason Hartley Jason Hartley - 1 month ago 11
Android Question

Assign view IDs in XML, access programmatically as integers

I want to be able to assign view IDs in XML, but access them programmatically as integers for the sake of iterating over them easily.

Here's the direction I was going which does not work:

values/value.xml:

<resources>
<integer name="int1">101</integer>
<integer name="int2">102</integer>
...
<integer name="int10">110</integer>
</resources>


layout/fancy_dialog_fragment.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" ...etc.>

<Button android:id="@integer/int1" ... />
<Button android:id="@integer/int2" ... />
...
<Button android:id="@integer/int10" ...etc. />


</LinearLayout>


FancyDialogFragment.java:

for (int i = 0; i < 10; i++ ) {
button[i] = (Button) getDialog().findViewById(100+i);
button[i].setText("foo");
}

Answer

How about this?

This goes into res/values/arrays.xml (you can call it whatever you want of course):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="myIds">
        <item>int1</item>
        <item>int2</item>
        <item>int3</item>
        <item>int4</item>
        <item>int5</item>
        <item>int6</item>
        <item>int7</item>
        <item>int8</item>
        <item>int9</item>
        <item>int10</item>
    </string-array>
</resources>

That's how the layout looks like:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" ...etc.>
    <Button android:id="@+id/int1" .../>
    <Button android:id="@+id/int2" .../>
    <Button android:id="@+id/int3" .../>
    <Button android:id="@+id/int4" .../>
    <Button android:id="@+id/int5" .../>
    <Button android:id="@+id/int6" .../>
    <Button android:id="@+id/int7" .../>
    <Button android:id="@+id/int8" .../>
    <Button android:id="@+id/int9" .../>
    <Button android:id="@+id/int10" .../>
</LinearLayout>

And there's the code:

Resources res = getResources();
String packageName = getPackageName();
String[] ids = res.getStringArray(R.array.myIds);
for (String id : ids) {
    int idInt = res.getIdentifier(id, "id", packageName);
    Button button = (Button) findViewById(idInt);
    button.setText("foo");
}
Comments