在你的LibGdx類中定義一個回調接口,並用它來通知你的AndroidLauncher開始新的活動。
例如在LibGdx遊戲類:
// Your Game class in the core package
public class MyGame extends Game {
// Define an interface for your various callbacks to the android launcher
public interface MyGameCallback {
public void onStartActivityA();
public void onStartActivityB();
public void onStartSomeActivity(int someParameter, String someOtherParameter);
}
// Local variable to hold the callback implementation
private MyGameCallback myGameCallback;
// ** Additional **
// Setter for the callback
public void setMyGameCallback(MyGameCallback callback) {
myGameCallback = callback;
}
@Override
public void create() {
...
}
...
private void someMethod() {
...
// check the calling class has actually implemented MyGameCallback
if (myGameCallback != null) {
// initiate which ever callback method you need.
if (someCondition) {
myGameCallback.onStartActivityA();
} else if (someOtherCondition) {
myGameCallback.onStartActivityB();
} else {
myGameCallback.onStartSomeActivity(someInteger, someString);
}
} else {
Log.e("MyGame", "To use this class you must implement MyGameCallback!")
}
}
}
然後確保您的AndroidLauncher實現所需的接口:
// Your AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements MyGame.MyGameCallback {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// create an instance of MyGame, and set the callback
MyGame myGame = new MyGame;
// Since AndroidLauncher implements MyGame.MyGameCallback, we can just pass 'this' to the callback setter.
myGame.setMyGameCallback(this);
initialize(myGame, config);
}
@Override
public void onStartActivityA() {
Intent intent = new Intent(this, ActivityA.class);
startActivity(intent);
}
@Override
public void onStartActivityB(){
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
}
@Override
public void onStartSomeActivity(int someParameter, String someOtherParameter){
Intent intent = new Intent(this, ActivityA.class);
// do whatever you want with the supplied parameters.
if (someParameter == 42) {
intent.putExtra(MY_EXTRA, someOtherParameter);
}
startActivity(intent);
}
}
感謝您的建議。看起來它會起作用,但需要嘗試使用您的建議。另外,請問爲什麼在這種情況下需要一個接口?我會感謝您的迴應:) – denden130 2014-09-27 03:36:36
我試過使用它,但我得到了MyGame SomeMethod()myGameCallback.onStartActivityA()的NullPointerException; 。事實證明myGameCallback爲空。我應該如何初始化它? – denden130 2014-09-27 05:28:52
哎呀是的,抱歉,我忘了指定。你可以添加一個setter。我會更新我的答案來證明這一點。 – 2014-09-27 09:10:41