views:

57

answers:

2

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

+1  A: 

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.");
EboMike
A: 

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

DroidIn.net