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

How to create a dialog box in a non-UI thread in a different class?(如何在不同类的非 UI 线程中创建对话框?)
本文介绍了如何在不同类的非 UI 线程中创建对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

There are 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 context;
   private Handler handler;

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

以及从活动初始化时

MyGame game = new MyGame(this);

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

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)