In Android, there seem to be three common ways to handle button clicks, what's the difference between the methods? And are any of them βbetterβ somehow?
The three methods that I see are as follows:
Anonymous class
Find the button by this identifier, then pass the new anonymous class to setOnClickListener , for example. in onCreate
findViewById(R.id.myButton).setOnClickListener(new OnClickListener() { public void onClick(View v) {
Deploy OnClickListener
Add OnClickListener and pass this to setOnClickListener , then use the switch setOnClickListener based on the button id, for example. in onCreate
findViewById(R.id.myButton).setOnClickListener(this);
and implement onClick as
public void onClick(View v) { switch(v.getId()) { case R.id.myButton:
Use atClick XML attribute
In the XML layout for your activity, instead of giving your button an identifier, use onClick as follows:
<Button android:layout_width="fill_parent" android:layout_height="fill_parent" android:onClick="buttonClicked" android:text="Button" />
Then in your Acitiviy there is a buttonClicked method:
public void buttonClicked(View v) {
I currently tend to use the XML attribute, but that is only because it includes the least amount of code. When should other methods be used?
Wilka source share