-->

A Simple Listener in Java (Android)

16 2019

1. Create an Interface “Listener”

public interface Listener {
    void Callback_SuccessEvent();
    void Callback_FailedEvent();
}

2. Create a Class “TestListener”

public class TestListener implements Listener {

    // add a private listener variable
    private Listener mListener = null;

    // provide a way for another class to set the listener
    public void SetListener(Listener listener)
    {
        this.mListener = listener;
    }

    public void TestMyListener(int n) 
    {
         if(n%2)
              mListener.Callback_SuccessEvent();
         else
              mListener.Callback_FailedEvent();
    }

 
}

3. Create a Main Class “TestMain”

public class TestMain implements Listener {

    public void MainFunction()
    {
          TestListener.SetListener(new Listener(){
                        @Override
                        public void Callback_SuccessEvent() {
                            Log.i("Callback", "Success");

                        }

                        @Override
                        public void Callback_FailedEvent() {
                            Log.i("Callback", "Failed");
                        
                        }
                    });
         TestListener.TestMyListener(2);
         TestListener.TestMyListener(3);
   } 
}

Leave a Reply