0

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

2 Answers 2

2

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.");
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.