You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何关闭使用Anko布局DSL自定义的AlertDialog?

How to Close Your Custom Layout AlertDialog (Anko DSL)

Hey there! Since you're using Anko's handy DSL to build that AlertDialog with a custom layout, closing it is straightforward once you hold onto the dialog instance. Let me walk you through the simplest and most reliable ways:

1. Hold a Reference to the Dialog & Call dismiss()

The key here is capturing the Dialog object that gets returned when you call .show() on your alert DSL. You can then use that reference to close the dialog whenever you need—like when the user taps your button, or after processing their input.

Here's how to adjust your code:

// Capture the dialog instance when you show it
val quantityDialog = 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 quantityInput = editText {
                inputType = InputType.TYPE_CLASS_NUMBER
                background = ContextCompat.getDrawable(this@ProductsList, R.drawable.textbox_bg)
            }.lparams(width = matchParent)

            // Add your button (or trigger) to close the dialog
            button("Submit") {
                // First, handle any input logic here if needed
                val enteredQuantity = quantityInput.text.toString()
                // Then close the dialog
                quantityDialog.dismiss()
            }
        }
    }
}.show()

2. Closing From Outside the Dialog Scope

If you need to close the dialog from somewhere else (like an async task completion, or a button in your parent activity), just make sure the quantityDialog variable is in a scope that's accessible to that code. For example, declare it as a property in your Activity/Fragment instead of a local variable, and you can call quantityDialog.dismiss() whenever required.

Quick Best Practice

Always remember to dismiss the dialog if your Activity/Fragment is being destroyed—this prevents memory leaks. You can do this in onDestroy() or onPause():

override fun onDestroy() {
    super.onDestroy()
    if (::quantityDialog.isInitialized) {
        quantityDialog.dismiss()
    }
}

内容的提问来源于stack exchange,提问作者Alex Kombo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:38:40