警报对话框构建器中使用的语法

问题描述 投票:-1回答:2

我难以理解用于调用AlertDialog.Builder的语法。这段代码显示在此链接中:https://android--code.blogspot.com/2018/02/android-kotlin-alertdialog-example.html

他打电话时builder.setPositiveButton(),他使用以下代码:

builder.setPositiveButton("YES") { dialog, which ->
   Toast.makeText(applicationContext, "Ok, we change the app background.", Toast.LENGTH_SHORT).show()
   root_layout.setBackgroundColor(Color.RED)
}

我的问题是:

1:dialog, which ->是什么意思?

2:当我调用方法时,传递{ something }是什么意思?它将与自己的功能一起执行吗?

谢谢。

android kotlin android-alertdialog
2个回答
1
投票

该代码利用了Kotlin的SAM转换功能,对于使用仅具有一种方法的接口,这只是一种更简洁的语法(请参阅this article以获取详细说明)。在这种情况下,单击对话框的肯定按钮时,将执行以下代码:

Toast.makeText(applicationContext,"Ok, we change the app background.",Toast.LENGTH_SHORT).show()
root_layout.setBackgroundColor(Color.RED)

dialogwhichDialogInterface.OnClickListener的两个参数。如果需要,可以在执行的块中引用它们。

完全写出来,看起来像这样:

builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(applicationContext,"Ok, we change the app background.",Toast.LENGTH_SHORT).show()
        root_layout.setBackgroundColor(Color.RED)
    }
});

0
投票

以下是DialogInterface.OnClickListener.onClick的文档

public abstract void onClick(DialogInterface对话框,其中)

单击对话框中的按钮时将调用此方法。

参数

  1. dialog DialogInterface:收到点击的对话框
  2. which int:被单击的按钮(例如DialogInterface#BUTTON_POSITIVE)或单击的项目的位置

您的示例使用lambda来传递此方法的实现

{
dialog, which -> // both of these are parameters of method,
                    and code after -> sign is body of the method


Toast.makeText(applicationContext,"Ok, we change the app background.",Toast.LENGTH_SHORT).show()
root_layout.setBackgroundColor(Color.RED)
}
© www.soinside.com 2019 - 2024. All rights reserved.