如何在视图内显示对话框?

问题描述 投票:0回答:1

我是android编程的新手,在第一个编程中,我试图做一个简单的Pong-Clone。我的程序通过不同的操作方法和我自己能应付的一点点拼接在一起。

基准:当我按下“播放”按钮时,它将调用我的“ GameActivity”,该游戏将“ GameView”设置为其ContentView。在GameView内,我可以处理游戏,球弹跳,玩家和敌人的一切。但是我的问题是,一旦一名玩家获胜,如何摆脱困境。

起初,我只是想简单地调用一个对话框,询问玩家是否要再次玩或返回菜单,但是我不能做任何与Activity相关的事情,因为im在“ GameView”中。如果我尝试这样做总是告诉我不能,因为“无法从静态上下文中引用非静态方法”。

所以我的GameActivity非常简单:



public class GameActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(new GameView(this));


    }
}

起初,我只是将这样的内容放入我的视图中:

        InfoDialog infoDialog = new InfoDialog();
        infoDialog.show(getSupportFragmentManager(), "infoDialog");

但是据我所知,我无法在View中做到这一点。

TLDR:如何从我的活动中停止或更改ContentView或在该视图内调用对话框?

[就像我说过的那样,我对Android编程非常陌生,如果我做这件事的方式非常复杂,那么抱歉。

java android android-activity view dialog
1个回答
0
投票

您可以在GameView构造函数上保存此活动的上下文,并在需要时使用它:

class GameView extends View {

    private Context mContext;

    //Constructor
    public GameView (Context context) {
        super(context);
        mContext = context
    }

    //Can be called inside the view
    public ShowDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage("Alert message to be shown");
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
        });
        alertDialog.show();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.