Android:将参数传递给Alert Dialog

时间:2015-01-26 03:41:41

标签: android android-ui android-dialog

我正在显示一个带有确定/取消按钮的简单警报对话框。 当用户单击“确定”时,会运行一些代码 - 这需要一个参数。

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        MainActivity.this);
        alertDialogBuilder
        .setTitle("Are you sure?")
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //TODO: Do something with parameter.
            }
        })
        .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();

                    }
                });

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();

// show it
alertDialog.show();

如何将参数传递给AlertDialog?

2 个答案:

答案 0 :(得分:10)

如果您将变量声明为final,那么您可以在调用AlertDialog.Builder()之前在代码中设置它,然后在onClick()中访问它,如下所示:

    final int someParameter = someValue;

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            this);
            alertDialogBuilder
            .setTitle("Are you sure?")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Do something with parameter.
                    doSomeStuff(someParameter);
                }
            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();

                        }
                    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

这样,someParameter通过函数closure隐式传递给onClick(),因此不需要子类AlertDialog或向Activity添加额外的成员变量。

答案 1 :(得分:-1)

您也可以在应用程序中使用静态变量。定义 public static String SumValue="";

假设我的调用类是 MainActivity 类,那么我可以在调用对话框之前启动变量

MainActivity.SumValue="测试值"; addcartdialog addcartdialog = 新的 addcartdialog(); addcartdialog.show(((AppCompatActivity) context).getSupportFragmentManager(),"添加购物车");

在 addcartdialog 类中

你可以分配给 textView = view.findViewById(R.id.servingsTxt); textView = MainActivity.SumValue;

通过这种方式,您可以在警报对话框中处理多个变量。

相关问题