Why We Should Use Custom Listeners?

If you are getting data by using a web service, you should wait until the data is successfully fetched (or even if it’s not successful) then take your next action. How would you implement it? Maybe by using an OnDataLoadedListener ?🧐.

The custom listener (listener/observer pattern) is used to emit events to a single parent for the purpose of communicating information asynchronously in order to run the code when an event occurs which helps us to move complicated logic out from our code. This Java pattern can be used in so many cases such as the communication from a fragment to activities, between two fragments through activity, between an adapter and an activity, Etc in Android. There are already several installed listeners within the Android and the very familiar one is when we want to attach a click event to a view which will be looking like the below snippet code:

Implement a Custom Listener in Android

The most important key in custom listener implementation is the interface.

Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations.

The interface can be defined individually in a separate file in the communication between the two classes, or it can be placed in one of those classes. This class is where we want to call the specific event there, and in our example, it will be an adapter. So let’s define an interface with methods we need in the listener as the following:

As you can see after creating an interface and its method which is called onPhraseClick(int position), I have created a listener instance that will be valued in the setter method of that listener(3rd step). At the last point here I have called the interface method inside the onClick(View v) method of one of my views and pass the position of the current item inside the adapter. When that item is clicked, the next activity will be created and this part will be handled in a related activity to that adapter as below:

By implementing OnPhraseClickListener in our activity, its method will be overridden there(2nd step) and then we can access the passed parameters. Last but not the least, set that listener to the adapter instance.

Notice that there are a lot of situations that you might need to use Custom Listeners not only in Android but also when you code Java natively and I have just shown a very general sample in Android.

Do not hesitate to share your ideas 🤪.

A self-learner

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store