Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onClickListener implementation best practices

There are four ways to add an onClickListener to a clickable View (button, for example):

  1. set the onClick attribute in the layout file which points to a method in the activity,
  2. create an anonymous inner class,
  3. assign the onClickListener to a private member variable.
  4. have the Activity context implement the onClickListener interface.

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?

like image 704
JaeW Avatar asked May 03 '16 20:05

JaeW


Video Answer


1 Answers

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:

  • consistency with activity/fragment;
  • access to the members of activity/fragment;
  • readability;
  • @Michael Krause showed one more good point about memory leaks;

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.

like image 161
Maxim G Avatar answered Oct 15 '22 11:10

Maxim G