I have added some buttons with the following lines:
for (int i=0; i<XML.size(); i++) {
//add button
ToggleButton b = new ToggleButton(this);
// Setting the parameters
lefttextv.setLayoutParams(lleft);
b.setLayoutParams(bright);
//customize button
b.setOnClickListener(this);
b.setId(id_button);
System.out.println(id_button);
b.setHeight(100);
b.setWidth(200);
// Adding to the RelativeLayout as a child
layouth.addView(lefttextv);
layouth.addView(b);
id_button++;
}
But how can I get the OnClick() methods for those? I already implemented View.OnClickListener with this method:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case id_button: Log.d("Button 0","Button 0 pressed);
break;
}
}
But this does not work, how do I get the Id?
b
is the view, if your onClick method is in your main class just use b.setOnClickListener(this);
and let your activity implement onClickListener and there you have it. Or do the usual way you set tour listeners.
The id is used for xml reference, the object is created and your using this id to reference, in your case you created the view b
with all the properties of a ToggleButton. It is the view.
Instead if using v.getId()
just useif(v == b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With