Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get OnClick() from programmatically added buttons?

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?

like image 875
Mokkapps Avatar asked Sep 24 '12 11:09

Mokkapps


1 Answers

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)

like image 117
FabianCook Avatar answered Oct 07 '22 16:10

FabianCook