-1

This what I have seen in an android application. They have a number of image buttons with ids

R.java :
        public static final int img1=0x7f090080;
        public static final int img2=0x7f090081;
        public static final int img3=0x7f090082;
        public static final int img4=0x7f090083;
        public static final int img5=0x7f090084;
        public static final int img6=0x7f090085;
        public static final int img7=0x7f090086;
        public static final int img8=0x7f090087;

In one of the activity they are traversing a for loop like below:

for (int i = 0; i < NoOfButtons; i++) {
    if (i == pos) {
        ((ImageView) vi.findViewById(R.id.img1 + i)).setImageResource(R.drawable.circular_pagination_red);
    } else {
        ((ImageView) vi.findViewById(R.id.img1 + i)).setImageResource(R.drawable.circular_pagination_brown);
}

I want to know how much safe and advisable it is. One thing this is working absolutely fine. I been a part of this from months and never seen a problem in this logic. But still it irks me a bit.

Note : I am not getting any error and I know the alternate solution also. My only concern is if it is not advisable/safe I want to know why? Another is scenarios where it can create havoc for me. I have a good understanding about R.java.

theJango
  • 1,100
  • 10
  • 22

2 Answers2

2

Though this might work OK most of the times, this is definitely not advisable. The R class is generated automatically thus you have no control over it and it could change. There is a solution to this problem using a typed array in resources. Check for example this answer.

Community
  • 1
  • 1
Lamorak
  • 10,957
  • 9
  • 43
  • 57
2

You might want to use reflection.

Add this method to your code:

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
        );
    }
    else
    {
        return ResourceID;
    }
}

And use it like this:

int myID =
    getResourceID("your_resource_name", "drawable", getApplicationContext());

Note: no path (and no extension, in case of images).

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115