Chris
Chris

Reputation: 13

Android accessing buttons created dynamically

If I create buttons dynamically in a loop,

for(i=0; i < size; i++) {

Button button = new Button(this);
myLayout.addView(button);

}

How can I reference each of these buttons at a later time? So, for eg, if I wanted to change the text on a few buttons, how would I do that?

Thanks Chris

Upvotes: 0

Views: 1952

Answers (2)

Bostone
Bostone

Reputation: 37126

You can refer to these in the same activity source file by creating class level field(s) or class level array. Beyond the original file I can't see need to refer to these buttons but say you have some sort of helper class you can always pass the Button object as reference in the constructor or method call. In other words - the Button object(s) you create is not any different from any other object if you are not getting in some weir serialization stuff which would be wrong anyway

Upvotes: 0

EboMike
EboMike

Reputation: 77722

Store an array of them?

Button buttons[] = new Button[size];

for(i=0; i < size; i++) {
   buttons[i] = new Button(this);
   myLayout.addView(buttons[i]);
}

buttons[0].setText("That was easy.");
buttons[1].setText("Yup.");

Upvotes: 2

Related Questions