1

If I set a custom click listener within the method decleration it works. But if I define the custom click listener as a private field and set it, it doesn't work. why?

public class CustomView {

  private View mView;
  private Button mButton;

  public CustomView() {
    mButton = new Button();
    mView = new View();
    // this works
    mView.setOnClickListener(new CustomClickListener() {
       @Override
       public void onClick() {
         mButton.setText("xyz");
       }
    });

    // this doesn't work as in nothing happens.
    mView.setOnClickListener(mCustomListener);
  }

  private CustomClickListener mCustomListener = new CustomClickListener() {
   @Override
   public void onClick() {
     mButton.setText("xyz");
   }
  };
}
user3995789
  • 3,452
  • 1
  • 19
  • 35

1 Answers1

0

Your problem is the order in which things happen. What will happen is:

First your constructor starts running, basically making a super call.

Then all your fields are initialized, so mCustomListener is init'ed before your assign a value to mButton!

One way to fix this:

private final mButton = new Button();
private final mCustomerListener = ...

and then within your ctor, just do the

mView.setOnClickListener(mCustomListener);

So, in other words: the problem with your code is that the field init for mCustomListener runs before you init mButton.

See here for further details on "order".

(hint: I recommend to make any fields final, simply because that is a good practice. Only allow fields to be changed later on ... when there is a good reason to do so; otherwise, keep your stuff final).

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248