无法获取警报对话框的按钮以防止对话框在 Kotlin 中关闭

Unable to get the button of the alert dialog to prevent the dialog from closing in Kotlin

我想创建一个在点击 positiveButton 时不会关闭的警告对话框。我根据我在网上找到的许多教程修改了我的代码。但是我无法获得按钮,builder.getButton

val builder = AlertDialog.Builder(this)
   with(builder) {
        setTitle("Hello....?")
        setCancelable(false)
        setPositiveButton("Done", null)
        setNegativeButton("Cancel", null)
        show()
        val positiveButton: Button = builder.getButton(AlertDialog.BUTTON_POSITIVE)
        positiveButton.setOnClickListener {
        }

您无法在生成器上获取按钮,您需要从对话框(您使用生成器创建的对话框)中获取它。将您的代码修改为:

val builder = AlertDialog.Builder(this)
        with(builder) {
            setTitle("Hello....?")
            setCancelable(false)
            setPositiveButton("Done", null)
            setNegativeButton("Cancel", null)
            val dialog = this.create()
            dialog.show()
            val positiveButton: Button = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
            positiveButton.setOnClickListener {
            }
}