簡體   English   中英

使用自定義 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()

您還可以將構建器的結果分配給類屬性等。請注意,局部變量的lateinit 自 Kotlin 1.2 起可用。

你可以簡單地做, it.dismiss() inside yes or no button callback,像這樣itDialogInterface

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM