Why use Inner Anonymous classes, and what are the alternatives?

advertisements

I've recently got into Android and have been looking at examples about Inner classes but don't really understand what the use of them is. They are used often when making listeners and when making a full class is unnecessary right? Maybe someone can explain it to me in laymans terms, also what would the alternative to using an inner anonymous class in this situation be? This code:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

Thanks


One alternative pattern is to make the container class itself a listener.

public class MyClass implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        // Do something when button is clicked
    }

    public void initOrSomething() {
        button.setOnClickListener(this);
    }
}

However you may run into trouble if you have more than one button that needs to behave differently.

Another way is to have different listener classes for each button

public class Button1Listener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        // Do something when button1 is clicked
    }
}

public class Button2Listener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        // Do something when button2 is clicked
    }
}

button1.setOnClickListener(new Button1Listener());
button2.setOnClickListener(new Button2Listener());

Anonymous inner classes are just a more compact representation of the second pattern.

EDIT: Variations of both patterns are possible, where contents of the View object are examined to determine which button was clicked or constructor arguments are passed to the listener class to change listener behavior etc.