user2558831 user2558831 - 5 months ago 8
Android Question

How to change the name of a button in a for loop in Java Android

I was wondering if you can help me. I want to simplify this code in java for android. Is there a way to do it?

btn1.setText(rnd[0]);
btn2.setText(rnd[1]);
btn3.setText(rnd[2]);
btn4.setText(rnd[3]);
btn5.setText(rnd[4]);


I was thinking in a for loop.

for(int i=0;i<5; i++) {
btn1.setText(rnd[i]);
}


But how can I change the number of btn? Is it possible?
Thanks.

Answer
final List<Button> myButtons = Arrays.asList(btn1, btn2, btn3, btn4, btn5)
for(int i = 0; i < 5; i++) {
   myButtons.get(i).setText(rnd[i])
}