The Listener Pattern in Android

(with Nic Cage & Kotlin)

mvndy
2 min readMar 13, 2019

Android applications are known to be event driven, waiting on the user to trigger an event. Since Android applications wait for events to be triggered, listeners are implemented with interfaces. One of the more important concepts to understand in Android is the ability to use listeners and callbacks, a concept that is very familiar with Java interfaces.

While Android has a lot of event listeners ready for you to already use like View.OnClickListener { … }, I think it really helps to understand what’s going on underneath the hood by implementing a custom Android listener from that mildly comical, but mostly weird bee scene with Nic Cage in the classic 2006 remake of The Wicker Man.

NOT THE BEEEEEEEEESSSSS

Implementing a Custom Android Listener

We start with defining an interface where we plan on setting the listener, with whatever methods you might need in the listener.

class WickerMan: Activity {
interface Listener {
fun onTheBees(status: String)
}

}

Add a private listener member variable and a public setter method to the child class. In particular, Android typically casts listeners to the activity or fragment of the listener class.

class WickerMan: Activity {    var listener: Listener? = null;    interface Listener {
fun onEatingBees(status: String)
}
override fun onAttach(activity: Activity) {
super.onAttach(activity);
listener =
activity as Listener
}

}

Then, we add a trigger in the class to be fired your event.

class WickerMan: Activity {    ... // listener stuff set up    fun beeeeeeeees() {
...
listener?.onEatingBees("NOT THE BEEEES!")
}

}

Now, you can implement the listener callback in any parent class, granted you expect that the method onEatingBees may be called at some point while the parent class is active.

class NicCage: WickerMan.Listener {
...
override fun onEatingBees(status: String) {
Log.d(status)
haveATotalMeltdown()
}

}

Now that we get the listener pattern a little more, let’s try instantiating a new fragment with a listener.

--

--

mvndy

software engineer and crocheting enthusiast. co-author of "Programming Android with Kotlin"