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.

4 Answers 4

7
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
        }
    }
};
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

Comments

0
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);
    }
}

Comments

0

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

<Button android:id="@id/button" android:text="@string/button" android:onClick="someMethod" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.