gpt4 book ai didi

java - 如何在 View 中显示对话框?

转载 作者:行者123 更新时间:2023-11-30 05:19:52 25 4
gpt4 key购买 nike

我是 android 编程新手,对于第一个程序,我试图做一个简单的 Pong-Clone。我的程序是由不同的操作方法和我自己能够处理的一点点缝合在一起的。

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

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

所以我的 GameActivity 非常简单:



public class GameActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

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


}
}

首先,我只是将这样的内容放入我的 View 中:

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

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

TLDR:如何从 Activity 中停止或更改 ContentView 或调用该 View 内的对话框?

就像我说的,我对 Android 编程非常陌生,如果我这样做的方式非常复杂,我很抱歉。

最佳答案

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

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

关于java - 如何在 View 中显示对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com