Definire un'interfaccia di callback nella classe LibGdx e utilizzarla per notificare all'avvio di AndroidLauncher la nuova attività.
Per esempio nella classe LibGdx gioco:
// 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!")
}
}
}
Poi Assicuriamo il vostro AndroidLauncher implementa l'interfaccia desiderata:
// 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);
}
}
fonte
2014-09-27 00:40:01
Grazie per il suggerimento. Sembra che funzionerà, ma devi provare a utilizzare il tuo suggerimento. Inoltre, potrei chiedere perché è necessaria un'interfaccia in questo caso? Apprezzerò la tua risposta :) – denden130
Ho provato ad usarlo ma ottengo NullPointerException su MyGame SomeMethod() myGameCallback.onStartActivityA(); . Si scopre che myGameCallback è nullo. Come dovrei inizializzarlo? – denden130
Oops si, scusa, ho dimenticato di specificarlo. Puoi semplicemente aggiungere un setter. Aggiornerò la mia risposta per mostrarlo. –