views:

301

answers:

4

Is there a way to have 1 onClick Lister for many buttons where I can toss a case statement to do things based on what buttons were clicked.

I know I can make 100 different listeners for 100 buttons but I have to think I can create some nifty variables to do it in less lines of code.

+2  A: 
Button btn1, btn2;
public void onCreate(Bundle b)
{
    // here you do normal things like assigning a
    // content view to the activity, initiate buttons, etc.

    // then you assign the same listener to both buttons
    btn1.setOnClickListener(yourListener);
    btn2.setOnClickListener(yourListener);
}

// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
    public void  onClick  (View  v){
        if( v == btn1 ){
            // do something 
        }
        elseif( v == btn1 ){
            // do another thing
        }
    }
};
Cristian
This worked great for me. Thanks.
dweebsonduty
A: 
public class MainActivity extends Activity implements View.OnClickListener{

btnXXX.setOnClickListener(this);

public void onClick(View v) {
    if (v.getId()==R.id.btnXXX){
        dialog.show();
    } else {
        handleOtherViews(v);
    }
}
Loxley
+1  A: 

If you are using 1.6+ version of the SDK you can use android:onClick to set the onClick handler of a view. In your activity you must have a method with the following signature. The view is the view that was clicked.

void onClick(View v) {
    switch(v.getId()) {
        case R.id.button1:
            //do something fantastic;
            break;
    }
}
BrennaSoft
+1  A: 

Alternatively, you can specify the method to call in xml:

<Button android:id="@id/button" android:text="@string/button" android:onClick="someMethod" />
alex
P.S. But this doesn't work in 1.5 SDK
davs