Android Custom Event Listener

别来无恙 提交于 2019-11-27 16:26:26

You should use interfaces.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!