如何从静态方法显示Dialog
作者:互联网
在我使用cocos2dx为Android和IOS完成的游戏中,我必须显示视频(适用于Android).我打算在Dialog中展示它(在游戏视图的顶部).问题是,我没有任何Activity参考show Dialog(因为Dialogs只能在Activities中显示).尽管如此,在cocos2dx lib文件夹中,有一个Cocos2dxActivity,但我没有得到如何使用它.从C代码,我从Java类调用静态方法,如下所示
void LMJNICommunicator::showVideo()
{
LOGD("initialiseDatabase inside LMJNICommunicator");
jmethodID methodID = 0;
JNIEnv *pEnv = 0;
pEnv = getJNIEnv();
jclass ret = pEnv->FindClass("com/mobinius/lostmonstersclass/LMDatabaseDataManager");
methodID = pEnv->GetStaticMethodID(ret, "showVideo", "()V");
if (! methodID)
{
LOGD("Failed to find static method id of %s", "showVideo");
return;
}
pEnv->CallStaticVoidMethod(ret,methodID);
pEnv->DeleteLocalRef(ret);
}
我从C代码调用的静态方法(在普通的Java类中)
Class LMDatabaseDataManager {
public static void showVideo() {
Dialog dialog = new Dialog(Cocos2dxActivity.getInstance());
dialog.show();
// getting Can't create handler inside thread that has not called Looper.prepare() error
}
}
我试图像this一样使用Handler但是没有得到结果(在该帖子中得到了相同的错误).
还尝试获得像this这样的静态上下文.
那么,我的方式是否正确?如果不正确,请建议一种方法如何实现相同的.谢谢.
编辑:
终于得到了答案.之前我尝试使用应用程序静态上下文在UI线程上运行,如this链接,但没有得到…使用Cocos2dxActivity活动实例我得到了它.
Class LMDatabaseDataManager {
public static void showVideo() {
Cocos2dxActivity.getInstance().runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Dialog dialog = new Dialog(Cocos2dxActivity.getInstance());
dialog.show();
}
});
}
}
解决方法:
尝试在Cocos2dxActivity中添加适当的行:
public class Cocos2dxActivity extends Activity {
private static Cocos2dxActivity instance = null;
@Override public void onCreate(Bundle b) {
...
this.instance = this;
}
public static Cocos2dxActivity getInstance() {
return instance;
}
}
当您想要创建对话框时:
if (Cocos2dxActivity.getInstance() != null) {
AlertDialog dialog = new AlertDialog(Cocos2dxActivity.getInstance());
// rest of your dialog code goes here
}
标签:cocos2d-x,android,java,android-context,dialog 来源: https://codeday.me/bug/20190826/1725516.html