如何关闭使用Anko布局DSL自定义的AlertDialog?
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

