Listening for some events
When listening for user-interface events in Android, you'll typically hook up a listener object of some sort to the widgets you want to receive events on. However, how the listener object is defined may follow a number of different patterns, and listeners can take a number of different forms. You'll often see a simple anonymous class being defined as the listener, which is something like this:
closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } });
However, while this pattern is common (especially because the much shorter lambda syntax was only introduced in Java 8, and Android didn't properly support it until 2017), it's not always your best choice for several reasons:
- This anonymous class is not reusable at all. It serves one purpose, for a single object in the entire application.
- You just allocated a new object that will also need to be garbage collected. This is not a big deal, but can sometimes...