【问题标题】:How to create a dialog box in a non-UI thread in a different class?如何在不同类的非 UI 线程中创建对话框?
【发布时间】:2015-05-11 16:31:05
【问题描述】:

我正在用 android 开发一个非常简单的游戏(在非 UI 线程中运行),我想这样做,当游戏结束时,它会显示一个带有分数的自定义对话框,但类是不在 MainActivity 类中。我不知道如何在没有任何错误的情况下在线程中创建对话框。

【问题讨论】:

    标签: android multithreading dialog


    【解决方案1】:

    有很多方法可以做到这一点。一种方法是将您的 context 传递给游戏的类构造函数,以便能够通过它访问 UI。

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

    以及从活动初始化时

    MyGame game = new MyGame(this);
    

    要在您的游戏类中显示对话框,只需使用此代码

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

    以及如何显示一个简单的 AlertDialog。

    private void showMyDialog() {
      new AlertDialog.Builder(context)
        .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();
    }
    

    【讨论】:

    • 一切正常,直到我使用处理程序在游戏线程上执行“showMyDialog”方法。它说我“无法访问的声明”。
    • 我已经解决了,我已经把它放在无限循环之后(它被设置为 true)。现在我有任何问题,谢谢!
    • 如果这是您问题的解决方案,请将其标记为正确答案。
    【解决方案2】:

    您需要返回 UI 线程以显示对话框,但您需要对当前 Activity(我假设为 MainActivity)的引用才能访问 UI 线程并用作对话框的上下文。检查方法runOnUiThread

    【讨论】:

    • 我如何引用?
    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多