There are four ways to add an onClickListener to a clickable View (button, for example):
So my question is, how do you choose one of these implementation techniques over another? Is there a best practices according to certain conditions, or is it just a matter of programmer preference?
Here we use so called callback pattern.
public class Button {
private Callback callback;
public Button(Callback callback) {
this.callback = callback;
}
public void update() {
// Check if clicked..
callback.onClick(this);
}
public interface Callback {
public void onClick(Button Button);
}
}
Button b = new Button(new Callback() {
@Override
public void onClick(Button b) {
System.out.println("Clicked");
}
});
In our case onClick handler implements the interface View.OnClickListener.
Key points:
1) Attribute in the XML file can be used only for activity, as @Karakuri mentioned it uses reflection which is slow.
2) Anonymous inner class has special rules for access to the members of enclosing class (check [1], [2]). There are some situations when memory leaks can happen (ex. threading with AsyncTask, Handlers).
3) Here you have a full access to the members of enclosing class.
4) Is a variation of 3d.
Readability depends on your handler size, small logic can be ok to inline, but for larger blocks of code consider 3d and 4th.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With