Hi,
Today i want to show you something very interesting in Android. I see that on the internet there are no tutorials for helping you to implement from A – Z your own listener.
Let me give an use case.
So you have two classes. One extends Activity in which you have a Button, and in the second one you need to listen to events, in our case you will listen to the event that a click was done in some Activity.
You will need to implement an interface and a singleton class like this:
public interface EventListener { public void onEventHappened(); }
This interface must be in a separate file (Interface)called EventListener
Now the class:
public class MyEvent { private EventListener listener; private static MyEvent instance; private MyEvent(){ } public static MyEvent getInsance(){ if (instance == null) instance = new MyEvent(); return instance; } public void setEventListener(EventListener listen) { listener = listen; } public void eventHappened() { if (listener != null) { listener.onEventHappened(); } } }
Now that you have those two classes copied in your project let me tell you how to use them.
So in the Activity where you have the Button in onClick method you put the code:
MyEvent.getInstance().eventHappened();
Now let s say that in any of your other classes you want to be notified about this event.
You will put in your other class the following code:
MyEvent.getInsance().setEventListener(new EventListener() { @Override public void onEventHappened() { //here is your code that will happen when the button from the other Activity was pressed } });