Jason Hartley Jason Hartley - 2 months ago 25
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:


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


<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. />



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


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"?>
    <string-array name="myIds">

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" .../>

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);