简体   繁体   中英

Creating a simple yes/no dialog box in a view (Android)

I've got an onCreateDialog method in my activity, which has a case switch to bring up different dialogs that I want to display depending on the request.

I cannot use the showDialog() method from my view because it's not accessible from the context that is passed when the view is created. At least, I can't find a way to access it.

How do I use showDialog from my application's view? Do I need to create a listener? And if so, how? Is there a better method?

Here is my onCreateDialog code that exists in my application's activity:

protected Dialog onCreateDialog(int id) {
    AlertDialog alert=null;
    switch(id) {
    case DIALOG_GAMEOVER_ID:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("You died. Play again?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       //init();
                       //oGameState = eGameState.PLAYING; 
                      dialog.cancel();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       finish();
                   }
               });
            alert = builder.create();
        break;
    default:
        break;
    }

    return alert;
}

I tried passing a reference to my activity, and I get crashes. Perhaps I am doing it wrong?

In my activity:

    // set our MainView as the View
    oNebulaMainView = new NebulaMainView(this, this);
    setContentView(oNebulaMainView);

In my view:

public NebulaMainView(Context context, Activity oActivity) {
    super(context);
    // adding the callback (this) to the surface holder to intercept events
    getHolder().addCallback(this);

    // create the game loop thread
    thread = new NebulaMainThread(getHolder(), this);

    setFocusable(true);

    oActivity.showDialog(DIALOG_GAMEOVER_ID);
}

I may be missing something here, but what is stopping you from just calling:

alert.show()

Just make the alert accessible to the view, and call that form inside your view.

将Alert声明为实例变量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM