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