Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android one OnClick method for multiple buttons?

I started program little bit in android, I have 3 buttons in a single activity.

I saw some example codes that assign the same OnClick event to all the buttons (even if they perform completely different action) and in the method Switch(id) case case case...

What is the better approach? one onClick method and switching or a lot of methods, one for each button?

Thanks.

like image 948
Ron Gross Avatar asked Oct 24 '11 09:10

Ron Gross


People also ask

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.

What does setOnClickListener do in Android?

setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface. If you have more than one button click event, you can use switch case to identify which button is clicked.

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.

What is the correct signature for a method used with the Android onClick xml attribute?

Using the android:onClick XML attribute where you just use the name of a public method with the signature void name(View v) or by using the setOnClickListener method where you pass an object that implement the OnClickListener interface.


1 Answers

Use this way:

@Override public void onCreate(Bundle savedInstanceState) {         button1.setOnClickListener(onClickListener);         button2.setOnClickListener(onClickListener);         button3.setOnClickListener(onClickListener); }  private OnClickListener onClickListener = new OnClickListener() {      @Override      public void onClick(View v) {          switch(v.getId()){              case R.id.button1:                   //DO something              break;              case R.id.button2:                   //DO something              break;              case R.id.button3:                   //DO something              break;          }     } }; 
like image 103
Nguyen Minh Binh Avatar answered Sep 19 '22 15:09

Nguyen Minh Binh