Difference Between OnClickListener vs OnClick:
OnClickListener is the interface you need to implement and can be set to a view in java code.
OnClickListener is what waits for someone to actually click, onclick determines what happens when someone clicks.
Lately android added a xml attribute to views called android:onclick, that can be used to handle clicks directly in the view's activity without need to implement any interface.
Both function the same way, just that one gets set through java code and the other through xml code.
setOnClickListener Code Implementation:
Button button = (Button) findViewById(R.id.mybutton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
yourMethod(v);
}
});
public void yourMethod(View v) {
// does something very interesting
}
XML Implementation:
// method to be written in the class
public void yourMethod(View v) {
// does something very interesting
}
//XML file
<?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="yourMethod" />
Both are the same in performance. Xml is pre-parsed into binary code while compiling. so there is no over-head in Xml.