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?
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.
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.
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.
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.
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; ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With