如何在不同 class 的非 UI 线程中创建对话框?

How to create a dialog box in a non-UI thread in a different class?

我正在 android 中开发一个非常简单的游戏(在非 UI 线程中运行),我想在游戏结束时显示自定义带有分数的对话框,但 class 不在 MainActivity class 中。我无法弄清楚如何在线程中创建对话框而不会出现任何错误。

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

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

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

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

并且从 activity

初始化时
MyGame game = new MyGame(this);

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

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();
}