使用自定义 Anko 布局 DSL 关闭警告对话框

Dismissing an alert dialog with custom Anko layout DSL

我创建了以下带有简单视图的警报对话框,其中包含 TextViewEditTextButton

alert {
            customView {
                verticalLayout {
                    textView {
                        text = getString(R.string.enter_quantity)
                        textSize = 18f
                        textColor = Color.BLACK
                    }.lparams {
                        topMargin = dip(17)
                        horizontalMargin = dip(17)
                        bottomMargin = dip(10)
                    }

                    val quantity = editText {
                        inputType = InputType.TYPE_CLASS_NUMBER
                        background = ContextCompat.getDrawable(this@ProductsList, R.drawable.textbox_bg)
                    }.lparams(width = matchParent, height = wrapContent) {
                        bottomMargin = dip(10)
                        horizontalMargin = dip(17)
                    }

                    button(getString(R.string.confirm)) {
                        background = ContextCompat.getDrawable(this@ProductsList, R.color.colorPrimary)
                        textColor = Color.WHITE
                    }.lparams(width = matchParent, height = matchParent) {
                        topMargin = dip(10)
                    }.setOnClickListener {
                        if (quantity.text.isNullOrBlank())
                            snackbar(parentLayout!!, getString(R.string.enter_valid_quantity))
                        else
                            addToCart(product, quantity.text.toString().toInt())
                    }
                }
            }
        }.show()

我想在单击按钮并执行 if-else 子句时关闭它。我尝试使用 this@alert 但它不提供对话框方法。

这是有问题的,因为您的 button 注册侦听器的函数调用在对话框甚至不存在时执行。

这是一种方法,使用本地 lateinit 变量使 dialog 在侦听器中可用:

lateinit var dialog: DialogInterface
dialog = alert {
    customView {
        button("Click") {
            dialog.dismiss()
        }
    }
}.show()

您还可以将构建器的结果分配给 class 属性 等。请注意,lateinit 可用于局部变量 since Kotlin 1.2.

你可以简单地做,it.dismiss()里面的yes or no按钮回调,就像这里itDialogInterface:

alert(getString(R.string.logout_message),getString(R.string.logout_title)){
        yesButton {
            // some code here
            it.dismiss()
        }
        noButton {
            it.dismiss()
        }
    }.show()