gpt4 book ai didi

java - Android-Libgdx,在游戏开始后点击按钮调用另一个 Activity

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:10 26 4
gpt4 key购买 nike

当我需要在游戏开始后单击按钮时调用另一个 Activity 时,我遇到了一个主要问题。游戏通过 AndroidApplication 接口(interface)的 initiate(game, ) 方法调用。

在正常的 Activity 中,我可以很容易地调用另一个 Activity,但似乎很难从实现了 AndroidApplication 的 Libgdx 类中调用另一个 Activity。

谁能建议一个正确的方法来从实现 AndroidApplication 接口(interface)的 Libgdx 类中调用 Activity?

我尝试这样做了一个星期,但似乎我的方法完全错误..

提前致谢。

最佳答案

在你的 LibGdx 类中定义一个回调接口(interface),并用它来通知你的 AndroidLauncher 开始新的 Activity 。

例如在您的 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 实现了所需的接口(interface):

// 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);
}

}

关于java - Android-Libgdx,在游戏开始后点击按钮调用另一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26069759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com