简体   繁体   中英

Android Custom Event Listener

I'm using AndEngine and Box2d in android application.
How to make my object "Player" to throw an event and the "GameScene" subscribes to it?

public class Player {

  @Override
  public void Collision(GameObject object) {
    if(object instanceof Coin) {
        //throws an event here
    }
  }
}

public class GameScene {
  private Player player = new Player();
  //catch the event here

}

You should use interface s.

Make an interface something like:

public interface Something
{
  void doSomething(GameObject object);
}

Where doSomething is the method which will be called (In this case could be objectCollision ) same for interface name ( ObjectCollider (?)).

then let GameScene implement it

public class GameScene implements Something

and implement the method.

In the Player class, add a listener to this:

public class Player {
 private Something listener;

And in the constructor ask for the listener:

public Player(Something listener) { this.listener = listener; }

Then to invoke it, just use

listener.doSomething(object);

Example:

public void Collision(GameObject object) {
   if(object instanceof Coin) {
     //throws an event here
     listener.doSomething(object);
   }
}

To create the Player object with this constructor you just need to do:

Player player = new Player(this); // if you implement the method in the class

You can use android life cycle for that.

Create a signal

interface IGameSignal{
    void gameHandler();
}

class GameSignal extends Signal<IGameSignal> implements IGameSignal{

    void gameHandler(){
        dispatch();    
    }
}

Than register to it in GameCence or anywhere else you want, there could be many listeners to same Signal .

class GameScene implements IGameSignal{
    GameSignal gameSignal = Factory.inject(GameSignal.class);

    void init() {
        newsUpdateSignal.addListener(this);        
    }

    public void gameHandler(){

    }
}

And dispatch the signal when you need, from where ever you need.

Class A{
    GameSignal gameSignal = Factory.inject(GameSignal.class);

    void execute(){
        // dispatch the signal, the callback will be invoked on the same thread
        gameSignal.gameHandler();
    }        
}

Disclaimer: I am the author of android life cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM