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

孤人 提交于 2019-12-20 05:38:20

问题


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.


回答1:


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

and when initializing from activity

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

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



回答2:


You need to go back to the UI thread to show the dialog, but you will need a reference to the current Activity (MainActivity I assume) to access to the UI thread and to use as a Context of the dialog. Check the method runOnUiThread



来源:https://stackoverflow.com/questions/30172967/how-to-create-a-dialog-box-in-a-non-ui-thread-in-a-different-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!