简体   繁体   English

在视图中创建简单的是/否对话框(Android)

[英]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. 我的活动中有一个onCreateDialog方法,该方法具有大小写切换,可以根据请求显示要显示的不同对话框。

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. 我无法在视图中使用showDialog()方法,因为无法从创建视图时传递的上下文中访问该方法。 At least, I can't find a way to access it. 至少,我找不到访问它的方法。

How do I use showDialog from my application's view? 如何在应用程序视图中使用showDialog? 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: 这是应用程序活动中存在的onCreateDialog代码:

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声明为实例变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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