如何在不同的类中创建一个非UI线程的对话框? [英] How to create a dialog box in a non-UI thread in a different class?

查看:169
本文介绍了如何在不同的类中创建一个非UI线程的对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的机器人(运行在非UI线程),我想要的是,当游戏是在一个非常简单的游戏,它显示了一个自定义对话框比分,但类ISN 'T在MainActivity类。我无法弄清楚如何创建线程的对话框whitout得到任何错误。

I'm developing a very simple game in android(that runs in a non-UI thread), I want to make that, when the game is over, it shows a custom dialog box with the score, but the class isn't in the MainActivity class. I can't figure out how to create the dialog in the thread whitout getting any error.

推荐答案

有这么多的方法来做到这一点。一种方法是通过您的上下文以游戏类的构造函数可以通过它来访问用户界面。

There is so many ways to do that. One way is to pass your context to the class constructor of the game to be able to access the UI through it.

public class MyGame {
   private Context mContext;
   private Handler handler;

   public MyClass(Context context) {
      this.mContext = context;
      handler = new Handler(Looper.getMainLooper());
   }
   ...
}

和从活动初始化时

MyGame game = new MyGame(this);

和展现在你的游戏类的对话框,只需使用该code

and to show the dialog in your game class, just use this code

handler.post(new Runnable() {
   public void run() {
      // Instanitiate your dialog here
      showMyDialog();
   }
});

这该怎么展示一个简单的AlertDialog。

and this how to show a simple AlertDialog.

private void showMyDialog() {
  new AlertDialog.Builder(mContext)
    .setTitle("Som title")
    .setMessage("Are you sure?")
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // continue with delete
        }
     })
    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // do nothing
        }
     })
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();
}

这篇关于如何在不同的类中创建一个非UI线程的对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆