I have written this code for a dynamic layout where I am using this loop to generate a pair of buttons (this is the part of code where I generate them)
for(int i = 1; i <= 2 ; i++) {
Button button1 = new Button(this);
button1.setTag("age");
button1.setId(i);
layout.addView(button1);
Button button2 = new Button(this);
button2.setId(i);
button2.setTag("country");
button2.setEnabled(false);
layout.addView(button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
What I wish to do is if button1 is clicked, button2 should get enabled (initially it is disabled).
This would be a very easy task to do if the buttons were created in xml as then they will have separate R.id.xxxxx names for each, but here I am unable to understand how to detect the other button in the OnClick(View v) method so that I can change if it is enabled or not, I have tried to add the tag for each button so that I have another parameter to recognize the buttons but I have no idea how to recognize the other button with the view information of the clicked button1.
I assume that you are using the button tags in your click processing. To keep the tag data and add the needed wiring between buttons, you can create a data structure that would serve as a tag:
Then you could reorganize your setup code:
The click processing will obviously need to be changed to cast
getTag()
to aButtonTag
instead of aString
.If you don't need the "age" and "country" information to distinguish button types, just set each button as the tag for the other.
EDIT:
With the latter scheme, here's how you would use this in a click listener:
If you needed the "age" and "country" part of the tag for other reasons, the code would be only a little different:
I got a solution to the problem after referring to this question here ( find button by ID or TAG ), it solves the problem I was facing as such !