【问题标题】:Android AlertDialog not showing upAndroid AlertDialog 未显示
【发布时间】:2021-12-17 04:34:35
【问题描述】:

我正在尝试在函数中打开警报对话框。在我的代码末尾调用 .show() 时,代码只是停止运行。 当我尝试在同一类的 onCreate 函数中执行完全相同的代码 sn-p 时,一切正常。当我试图从另一个函数打开对话框时,为什么它不会打开?

    DialogInterface.OnClickListener dialogClickListener = (dialog, which) -> {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                //Yes button clicked
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
        }
    };


    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();

【问题讨论】:

  • 你在哪里调用其他函数?请发布完整的功能。

标签: android android-alertdialog


【解决方案1】:

你可以试试这个,应该很简单:

  AlertDialog alertDialog = new AlertDialog.Builder(
                YourDialogActivity.this).create();

   alertDialog.setTitle("Alert Title");
   alertDialog.setMessage("Alert Message");

   alertDialog.setPositiveButton("YES",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(),
                    "YES clicked", Toast.LENGTH_SHORT)
                    .show();
        }
    });

   alertDialog.setNegativeButton("NO",
     new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(),
                    "NO clicked", Toast.LENGTH_SHORT)
                    .show();
            dialog.cancel();
        }
    });

   alertDialog.show();

请设置您在该功能不适合您的情况下如何使用它

【讨论】:

    【解决方案2】:

    试试这样:

             AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    
        builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
                .setNegativeButton("No", dialogClickListener);
        AlertDialog alert=builder.create();
        alert.show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 2012-12-15
      • 1970-01-01
      相关资源
      最近更新 更多