Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

java - 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

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...