【问题标题】:How to display a Dialog inside a View?如何在视图中显示对话框?
【发布时间】:2020-05-01 09:10:04
【问题描述】:

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

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

起初我想简单地调用一个对话框,询问玩家是否想再次玩游戏或返回菜单,但我当然不能做任何与活动相关的事情,因为我在“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");

但正如我所说,据我所知,我不能在视图中这样做。

TLDR:如何停止或更改 Activity 中的 ContentView 或在该视图中调用对话框?

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

【问题讨论】:

  • 您可以使用AlertDialog调用对话框
  • 但是,如果我在活动中调用它,它不会被调用,因为 setContentView 使它卡在我的 GameView 中,如果我在 GameView 中调用它,它不起作用,因为它需要一个活动作为上下文:/

标签: java android android-activity view dialog


【解决方案1】:

您可以在 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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多