Android-libgdx, Calling Another Activity After The Game Starts On Button Click
I faced a major problem when I need to call another activity when the button is clicked after the Game is started. The Game is called via initiate(game, ) method from AndroidApplic
Solution 1:
Define a callback interface in you LibGdx class, and use it to notify your AndroidLauncher
to start the new activity.
For example in your LibGdx game class:
// Your Game class in the core packagepublicclassMyGameextendsGame {
// Define an interface for your various callbacks to the android launcherpublicinterfaceMyGameCallback {
publicvoidonStartActivityA();
publicvoidonStartActivityB();
publicvoidonStartSomeActivity(int someParameter, String someOtherParameter);
}
// Local variable to hold the callback implementationprivate MyGameCallback myGameCallback;
// ** Additional **// Setter for the callbackpublicvoidsetMyGameCallback(MyGameCallback callback) {
myGameCallback = callback;
}
@Override
publicvoidcreate () {
...
}
...
privatevoidsomeMethod() {
...
// check the calling class has actually implemented MyGameCallbackif (myGameCallback != null) {
// initiate which ever callback method you need.if (someCondition) {
myGameCallback.onStartActivityA();
} elseif (someOtherCondition) {
myGameCallback.onStartActivityB();
} else {
myGameCallback.onStartSomeActivity(someInteger, someString);
}
} else {
Log.e("MyGame", "To use this class you must implement MyGameCallback!")
}
}
}
Then ensure your AndroidLauncher
implements the required interface:
// Your AndroidLauncherpublicclassAndroidLauncherextendsAndroidApplicationimplementsMyGame.MyGameCallback {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfigurationconfig=newAndroidApplicationConfiguration();
// create an instance of MyGame, and set the callbackMyGamemyGame=newMyGame;
// Since AndroidLauncher implements MyGame.MyGameCallback, we can just pass 'this' to the callback setter.
myGame.setMyGameCallback(this);
initialize(myGame, config);
}
@OverridepublicvoidonStartActivityA() {
Intentintent=newIntent(this, ActivityA.class);
startActivity(intent);
}
@OverridepublicvoidonStartActivityB(){
Intentintent=newIntent(this, ActivityB.class);
startActivity(intent);
}
@OverridepublicvoidonStartSomeActivity(int someParameter, String someOtherParameter){
Intentintent=newIntent(this, ActivityA.class);
// do whatever you want with the supplied parameters.if (someParameter == 42) {
intent.putExtra(MY_EXTRA, someOtherParameter);
}
startActivity(intent);
}
}
Post a Comment for "Android-libgdx, Calling Another Activity After The Game Starts On Button Click"