Android 自定义事件监听器 [英] Android Custom Event Listener
问题描述
我在 Android 应用程序中使用 AndEngine 和 Box2d.
如何让我的对象Player"抛出一个事件并且GameScene"订阅它?
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
}
推荐答案
你应该使用interface
s.
制作一个类似的界面:
public interface Something
{
void doSomething(GameObject object);
}
其中 doSomething
是将被调用的方法(在这种情况下可能是 objectCollision
)对于接口名称(ObjectCollider
(?)).
Where doSomething
is the method which will be called (In this case could be objectCollision
) same for interface name (ObjectCollider
(?)).
然后让 GameScene 实现它
then let GameScene implement it
public class GameScene implements Something
并实现该方法.
在 Player 类中,为此添加一个侦听器:
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; }
然后调用它,只需使用
listener.doSomething(object);
示例:
public void Collision(GameObject object) {
if(object instanceof Coin) {
//throws an event here
listener.doSomething(object);
}
}
要使用此构造函数创建 Player 对象,您只需要执行以下操作:
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
这篇关于Android 自定义事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!