0

i have some consecutive elements id declared inside R.java files. Now i need to fill each one by using a for cycle, so i need to increment for each iteration value of id. I've write this:

int current_id = R.id.button00;
for (int i = 0; i < values.length; i++) {
    TextView to_fill = (TextView) (getActivity().findViewById(current_id));
    to_fill.setText(String.valueOf(values[i]));
    current_id++;
}

but in this way current_id doesn't increment correctly. How can i do?

giozh
  • 9,868
  • 30
  • 102
  • 183

1 Answers1

1

There is no guarantee that the generated IDs in R will be sequential, or that they will be generated in any particular order.

I recommend putting your IDs in an array resource like so:

<array name="button_id_array">
    <item>@id/button00</item>
    <item>@id/button01</item>
    <item>@id/button02</item>
</array>

Then you can access it in code like so:

int[] ids = getResources().getIntArray(R.array.test);
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
  • id is ordered, it's something like: button00=0x7f040038; public static final int button01=0x7f04003a; public static final int button02=0x7f04003c; public static final int button03=0x7f04003e; public static final int button10=0x7f040040; public static final int button11=0x7f040042; – giozh Feb 12 '14 at 16:01
  • 1
    The first thing to notice is that it isn't incrementing by 1 (as you have written in your code)- it is incrementing by 2. Again, I highly recommend against trying to do this as it is prone to the ID generation mechanisms that you have no control over. – Bryan Herbst Feb 12 '14 at 16:09
  • 1
    Not only is incrementing hard id numbers unpredictable, but the sequence can *change* between fresh builds. I strongly agree with Tanis here. Even if you get it "working", there's no guarantee it will work later. – Geobits Feb 12 '14 at 16:35