【问题标题】:Android show dialog in Custom View自定义视图中的 Android 显示对话框
【发布时间】:2015-03-25 12:56:13
【问题描述】:

我创建了一个显示简单游戏的自定义视图

我在 MainActivity 中设置了自定义视图

setContentView(new CustomView())

在这个自定义视图中,只有很少的球和计时器

当一个球碰到另一个球时。计时器将停止并显示结果。

我不知道如何以更好的方式显示结果。所以我尝试创建一个对话框来显示结果。

这段代码写在CustomView类中

if (ballIsTouch) {
            AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
            alertDialog.setTitle("Result");
            alertDialog.setMessage(point);
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            alertDialog.show();
        }

但是,页面被冻结。对话框没有显示。

【问题讨论】:

    标签: dialog android-custom-view


    【解决方案1】:
    • create() - 是最后一步 - 当您使用构建器模式创建对话框时,您首先在链中设置所有变量,然后创建对话框 - 并显示它应该是

          AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
          alertDialogBuilder.setTitle("Result");
          alertDialogBuilder.setMessage(point);
          alertDialogBuilder.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
              new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                      dialog.dismiss();
                  }
              });
          AlertDialog alertDialog = alertDialogBuilder.create();
          alertDialog.show();
      

            alertDialogBuilder.setTitle("Result")
              .setMessage(point)
              .setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    

    确保您的 getContext() 有效(应该是活动、服务上下文)** 在活动中使用 thisMyactivity.this 在界面/回调片段 getActivity()

    **见Dialog creation context

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多