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

前端 未结 2 1570
别跟我提以往
别跟我提以往 2021-01-28 09:35

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 cla

2条回答
  •  走了就别回头了
    2021-01-28 10:40

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

提交回复
热议问题