Customizing listeners in your own class/object

I wanted to listen to a listeners which I implemented in my custom class without defining it on my MAIN class, so I come up with this idea of some sort of inheriting the listener and pass back to my main calling class. For the following example, I will show how to pass the listener (LocationManager.LocationListener) back to the MAIN. This is good if you want to have your custom class which will implements bunch of other listeners.

For example, I have Main and Class A.
Main – Main Class
MyLocationManager – Called from Main Class. Implements LocationManager.LocationListener
MyLocationManagerInterface – Where interface is declared

Main.java

public Main implements MyLocationManagerInterface{
  public MyLocationManager locationManager;

  public void onCreate(){
    locationManager = new MyLocationManager(this);
  }

  @Override
  public void onLocationChanged(Location location) {
    // Code here will be executed once LocationManager.LocationListener is called, even is not declared here.
  }
}

MyLocationManagerInterface.java

public interface MyLocationManagerInterface {
	public void onLocationChanged(Location location);
}

MyLocationManager.java

public MyLocationManager implements LocationListener{
  MyLocationManagerInterface myLocMgrIf;

  public MyLocationManager(MyLocationManagerInterface listener){
    myLocMgrIf = listener; // Init custom listener
    ......
    // Here you init all the LocationManager stuffs and request for updates.
  }

  @Override
  public void onLocationChanged(Location location) {
    myLocMgrIf.onLocationChanged(location); // Here you pass the location to custom interface
  }
}
Advertisements

Posted on July 21, 2014, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: