[英]Dismissing an alert dialog with custom Anko layout DSL
我創建了以下帶有簡單視圖的警告對話框,其中包含TextView
、 EditText
和Button
:
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,像這樣it
是DialogInterface
:
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.