From that I\'ve read you can assign a onClick
handler to a button in two ways.
Using the android:onClick
XML attribute where you just use t
Another way to set your on click listeners would be to use XML. Just add android:onClick attribute to your tag.
It is a good practice to use the xml attribute “onClick” over an anonymous Java class whenever possible.
First of all, lets have a look at the difference in code:
XML Attribute / onClick attribute
XML portion
Java portion
public void showToast(View v) {
//Add some logic
}
Anonymous Java Class / setOnClickListener
XML Portion
Java portion
findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Add some logic
}
});
Here are the benefits of using the XML attribute over an anonymous Java class:
Of course, it is not always possible to use the Xml attribute, here are the reasons why we wouldn’t chose it: