Android Nougat

android:onClick(XML) vs. OnClickListeners (code)

1. Activity as OnClickListener
You can make your Activity implement View.OnClickListener interface which is generally a good idea. It makes clear explanation that your Activity can receive messages from Buttons.

2. Use android:onClick attribute in XML definition of a Button.
In my opinion is the best solution.
Here we need to do two things: 1. in XML layout of our Activity when we define a Button we need to add an attribute: android:onClick="onButtonClick" where we define the name of the method we need to implement in our Activity. 2. Implement public void onButtonClick(View v) method in our Activity.


Clean and clear solution. Less code. Brilliant! :)




The advantage of 2th way to do it is that first you type less(Activity isn't implementing interface, you don't need to have a variable for your button, you don't do  findViewById and setOnClickListener etc.), which is always good and clean, second you don't deal with scopes too much so here it's just another public method in your Activity.
Also you always know where to find your action.
The down side is if you'd reuse xml layout where you've defined android:onClick attribute on a Button somewhere else you would have to implement the method defined in the attribute all the the time. Otherwise you'd get a crash because of unfound/unimplemented method.

Have fun:)

These two code snippets are totally the same but just implemented in two different ways.
Code Implementation:

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myFancyMethod(v);
    }
});

// some more code

public void myFancyMethod(View v) {
    // does something very interesting
}
Above is a code implementation of an OnClickListener. And not the XML implementation.
XML Implementation:


<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me!"
    android:onClick="myFancyMethod" />
<!-- even more layout elements -->
Now in the background Android does nothing else than the Java code calling your method on a click event.
Note that with the XML above, Android will look for the onClick method myFancyMethod() only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.

Comments