Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable OnClick Listener Android

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.

like image 586
shaneburgess Avatar asked Feb 26 '23 19:02

shaneburgess


2 Answers

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
        }
    }
};
like image 112
Cristian Avatar answered Mar 06 '23 21:03

Cristian


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;
    }
}
like image 35
Robby Pond Avatar answered Mar 06 '23 19:03

Robby Pond