Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One OnClickHandler for multiple Buttons

I find myself doing things like this all the time:

    Button button1 = (Button) findViewById(R.id.button1);     Button button2 = (Button) findViewById(R.id.button2);     Button button3 = (Button) findViewById(R.id.button3);      button1.setOnClickListener(menuButtonListener);     button2.setOnClickListener(menuButtonListener);     button3.setOnClickListener(menuButtonListener); ... 

and

   private OnClickListener myButtonListener = new OnClickListener() {         @Override         public void onClick(View v) {       switch(v.getId()){        case R.id.button1 :     ... 

Is there a better way to set the OnClickListener?

like image 540
mseo Avatar asked Sep 25 '10 20:09

mseo


People also ask

Can 2 buttons have the same ID?

Answer. As HTML and CSS are designed to be very fault tolerant, most browsers will in fact apply the specified styles to all elements given the same id. However, this is considered bad practice as it defies the W3C spec. Applying the same id to multiple elements is invalid HTML and should be avoided.

Can two buttons have same ID Android?

This is no longer possible,android lint checks prevent you from adding same ids in the same xml file. A work-around would be to use the include tag to include other xmls with repeating ids.

How do I turn off multiple click on Android?

The actual solution to this problem is to use setEnabled(false) which greys out the button, and setClickable(false) which makes it so the second click can not be received I have tested this and it seem to be very effective.


2 Answers

You can also set it in your layout xml using the android:onclick attribute.

android:onClick="onClick" 

Then in your activity class add the onClick method.

public void onClick(View v) { ... 

Here's the documentation.

like image 88
aprock Avatar answered Sep 18 '22 05:09

aprock


Have your class implement `View.OnClickListener', like

public class MyActivity extends Activity implements View.OnClickListener {      Button button1, button2, button3;      @Override     public void onCreate(Bundle bundle) {         super.onCreate();          ...          button1 = (Button) findViewById(R.id.button1);         button2 = (Button) findViewById(R.id.button2);         button3 = (Button) findViewById(R.id.button3);          button1.setOnClickListener(this);         button2.setOnClickListener(this);         button3.setOnClickListener(this);    }     @Override    public void onClick(View v) {        switch(v.getId()) {            case R.id.button1:            // do stuff;            break;            case R.id.button2:            // do stuff;            break;        ...    } } 
like image 21
Chris Fei Avatar answered Sep 22 '22 05:09

Chris Fei