• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Where's the best place to implement listener methods?

mavavilj

Lurker
Where's the best place to implement listener methods?

In one example I found, they're done inside the onCreate() method of the MainActivity class.

But intuitively it seems that this will lead to quite bloated code, when one has many views and many UI elements.

When I was writing C++ or Java GUIs before I used to inherit from the GUI element classes that I used as GUI elements and then implement the methods inside them. That made every GUI element have its own encapsulation.
 
Last edited:
You can create a specific event listener class, if you wish to partition the code and avoid bloating your main Activity class. So for example, I can write a Button click event listener class simply by implementing the View.OnClickListener class:

Code:
public class MyClickListener implements View.OnClickListener {

  ...
  public void onClick(View v) {
                 // Code here executes on main thread after user presses button
  }
}

Quite often, the listener code is quite trivial, so people tend to just use an anonymous class to provide the click event listener directly in the main Activity class. But as you point out, this can lead to code bloat, so writing a separate listener class can produce cleaner and more maintainable code.

https://developer.android.com/reference/android/widget/Button.html
 
In fact the above is quite flexible, and can be used for multiple different Buttons.
You can see that the onClick() method takes a View parameter, which is the Button object which generated the event. So your code can do something different, depending on the specific Button being clicked.
 
Back
Top Bottom