Basic Listener

suggest change

The “listener” or “observer” pattern is the most common strategy for creating asynchronous callbacks in Android development.

public class MyCustomObject {       
  
  //1 - Define the interface 
  public interface MyCustomObjectListener {
      public void onAction(String action);
  }

  //2 - Declare your listener object
  private MyCustomObjectListener listener;

  // and initialize it in the constructor
  public MyCustomObject() {
    this.listener = null;
  }

  //3 - Create your listener setter
  public void setCustomObjectListener(MyCustomObjectListener listener) {
    this.listener = listener;
  }

  // 4 - Trigger the listener event
  public void makeSomething() {
    if (this.listener != null) {
      listener.onAction("hello!");
    }
  }
}

Now on your Activity:

public class MyActivity extends Activity {
   public final String TAG = "MyActivity";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main_activity);
        

      MyCustomObject mObj = new MyCustomObject();
    
      //5 - Implement listener callback
      mObj.setCustomObjectListener(new MyCustomObject.MyCustomObjectListener() {
        @Override
          public void onAction(String action) {
              Log.d(TAG, "Value: "+action);
          }
      });
   }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents