How to get OnClick () from programmatically added buttons?

I added a few 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 them? I have already implemented View.OnClickListener using 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 identifier?

+5
source share
5 answers

b- this is a representation 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 in the usual way that you set the tour audience.

xml, , b ToggleButton. .

, v.getId(), if(v == b)

+7

b.setOnClickListener(this), this , OnClickListener.

Edit:

ID . . . switch/case.

, @SmartLemon, if (v == b), .

+6

u set idto buttonhow id_buttonright?

add onCreate Method:

 b1.setOnClickListener(this);    

Use this identifier in the onClick method, as shown below:

@Override
 public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.id_button)
    {
    Log.d("Button 0","Button 0 pressed);
        break;
    }
}
+3
source

When you implement onClickListener in your activity class, you can pass the current object with this keyword to register a click listener for the component.

class MyActivity extends Activity implements OnClickListener{
     private static final int id_button = 0;

     public void onCreate(Bundle b){
        //add button
        ToggleButton b = new ToggleButton(this); 
        // Setting the parameters
        lefttextv.setLayoutParams(lleft); 
        b.setLayoutParams(bright);
        //customize button
        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);
        b.setOnClickListener(this);
     }

     @Override
     public void onClick(View v) {
        // TODO Auto-generated method stub
       switch (v.getId()){
       case 0: Log.d("Button 0","Button 0 pressed);
            break;
       }
    }
}
+3
source

change like this ..

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    int i= b.getId();
    switch (v.getId())
    {
        case i:
            Log.d("Button 0","Button 0 pressed");
            break;
    }
}
+2
source

All Articles