我需要获取Context
我的应用程序的,但在我的主类中从扩展,Game
所以我不能从扩展Activity
。有人知道怎么做吗?
谢谢!
因为您无法从Core模块访问特定于Android的代码,所以必须使用接口。
步骤1:建立介面(CORE MODULE)
public interface MyInterface {
void manipulateContext();
void manipulateContextWithExtraParams(String example, int example2);
}
步骤2:实施介面(ANDROID MODULE)
import android.content.Context;
public class InterfaceImplementation implements MyInterface {
private Context context;
public InterfaceImplementation(Context context) {
// Store the context for later use
this.context = context;
}
@Override
public void manipulateContext() {
// Do something with the context, this is called on the core module
System.out.println(context);
}
@Override
public void manipulateContextWithExtraParams(String example, int example2) {
if (example2 == 1) {
System.out.println(example + context);
} else {
System.out.println(example);
}
}
}
步骤3:将实作的介面传送给您的游戏(ANDROID MODULE)
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.frontanilla.helping.getcontext.InterfaceImplementation;
import com.frontanilla.helping.getcontext.MyGame;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
InterfaceImplementation interfaceImplementation = new InterfaceImplementation(this);
// Here we send the implementation to our Game in Core module
initialize(new MyGame(interfaceImplementation), config);
}
}
步骤4:存储并使用您在界面上定义的方法(核心模块)
import com.badlogic.gdx.Game;
public class MyGame extends Game {
private MyInterface myInterface;
public MyGame(MyInterface myInterface) {
// Store for later use
this.myInterface = myInterface;
}
@Override
public void create() {
// Example of manipulating the Android Context indirectly from Core module
myInterface.manipulateContext();
myInterface.manipulateContextWithExtraParams("Hello", 2);
}
}
如您所见,您将不会Context
直接从核心模块操作,而是将逻辑放在InterfaceImplementation
类上
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句