Josh Derk
Josh Derk

Reputation: 37

I don't fully understand onClickListeners

So when we set an onClickListener to, say, a Button, it looks something like this.

private Button myButton = (Button) findViewById(R.id.my_button);

myButton.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View view){
        //do this
    }

});

So we're creating a nameless anonymous class when we state new View.OnClickListener... and implementing the OnClickListener interface / and overriding it's onClick method. What I don't understand, is if we have no reference to this anon class, because it's nameless, how does the onClick() method get called? I've only ever implemented an anonymous class to override certain methods in said class, like this:

public class Foo{
    public void bar(){
        //do something
    }
}


Foo foo = new Foo(){
    @Override
    public void bar(){
        //do something else
    }
}

This makes perfect sense to me because now, anytime I use the "foo" reference to call the bar() method, that reference will use the overridden version of bar. In the case of the Button, there's no reference to onClick(). I'm beyond confused about this.

Upvotes: 0

Views: 61

Answers (3)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26068

If it helps your understanding, you could rewrite to this:

View.OnClickListener listener = new View.OnClickListener(){
    @Override
    public void onClick(View view){
        //do this
    }
};
myButton.setOnClickListener(listener);

The button holds the reference after listener goes out of scope, and can call the onClick callback on the held listener object.

Upvotes: 4

Vinicius Zaramella
Vinicius Zaramella

Reputation: 531

The onclick event is called in the button object and this object delegates to your anonymous class onclick with the reference you set.

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006829

What I don't understand, is if we have no reference to this anon class, because it's nameless, how does the onClick() method get called?

myButton is holding onto the instance of the anonymous inner class that you created. myButton, therefore, can call onClick() on it.

Upvotes: 1

Related Questions