AbAppletic AbAppletic - 26 days ago 8
Android Question

Why do we implement View.OnClickListener if we can have to set android:onClick either way?

Edit: No, this is not a duplicate for the given link is asking for the comparison of

setOnClickListener
and
android:onClick
. I'm not even asking for a comparison, but I'm asking about the advantage of having an implementation of
View.OnClickListener
.

Please be free to vote to re-open.




Many people, by preference, use

public class TrumpLocator extends Clinton implements View.onClickListener{
@Override
public void onClick(View v){
//...
}
}


However, if I'm not mistaken, either way, on your
Button
you have to do:

android:onClick="onClick"


But, again if I'm not mistaken, if we don't override
onClick
and implement
View.onClickListener
, we will achieve the same effect:

//no override and no "implements onClickListener"
public void onClick(View v){
//...
}


and

android:onClick="onClick"


So, is there any advantage of implementing the method over simply applying the click listener? Isn't it just a waste of code?

Answer

either way, on your Button you have to do:

android:onClick="onClick"

No, this isn't required.

I think you have it backwards maybe. By having android:onClick="onClick", you need a public void method with that name in the quotes.

public void onClick(View v){
  //...
}

This is similar to implementing the interface, but not the exact same. In other words, it could just as well be android:onClick="handleClick", then you need

public void handleClick(View v){
  //...
}

People may not prefer this because it can lead to typos and uncertainty where a click listener is attached.


Now, the Activity does not need to implement the interface itself, you can attach anonymous class listeners to the views individually.

Comments