-1

I have a situation in an app I'm making where I have an activity that has 15 buttons and a string[] that contains 15 strings. I'm looking for an easy way to assign each string in the string[] to its corresponding button. I was hoping I could somehow do something like:

for(int i; i<myStringArray.length; i++){
    String ref = "btn" + (i + 1);
    ref.setText(resultString[i]);
}

where all the buttons are labeled "btn1", "btn2", etc so that they could all be accessed with the string "ref". Obviously this doesn't work so I was wondering if there was another way of doing something similar to this instead of doing:

btn1.setText(resultString[0]);
btn2.setText(resultString[1]);
btn3.setText(resultString[2]);
...

thanks for the help!

Ethan Shoe
  • 466
  • 1
  • 7
  • 20

2 Answers2

2

I think you can solve this by having a Button[] table where you store all your Button objects and then you can access them by index instead of the actual object name:

Button[] btns = new Button[15] for(int i = 0; i < btns.length; i++) { btns[i].setText(resultString[i]); }

Hope that helps.

EDIT: Ofcourse you have to fill your Button[] btns with your objects first.

Matic Tuma
  • 94
  • 1
  • 8
  • That's actually the best solution imo, as that links both arrays. Keep in mind tho that his button array starts at 1, oyu should change btns[i] as btns[i + 1] – Turtle May 24 '17 at 09:47
  • @Nathan `i` represents the index of the table not the number in the object's name so the `btn1` is stored in `btns[0]` thats why in the for loop I call `btns[i]` instead of `btns[i+1]` – Matic Tuma May 24 '17 at 09:53
  • Indeed, but I assumed from op's example that the `String ref` he built (from i) was the direct text of the button. – Turtle May 24 '17 at 12:00
0

You can do what you tried using reflection. It would be way better in your case to store your buttons in an Array or a Map instead though.

Turtle
  • 1,626
  • 16
  • 26
  • 1
    Answering that other question of you: yes, "too broad" would be one legit close reason for that question. – GhostCat May 24 '17 at 09:46