androidkotlinanko

Dismissing an alert dialog with custom Anko layout DSL


I have created the following alert dialog with a simple view comprising of a TextView, EditText and 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()

I want to dismiss it whenever the button is clicked and the if-else clause has been executed. I tried using this@alert but it doesn't provide the dialog methods.


Solution

  • This is problematic because your button function call which registers the listener executes when the dialog doesn't even exist yet.

    Here's one way to do it, using a local lateinit variable to make the dialog available inside the listener:

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

    You could also assign the result of the builder to a class property, etc. Note that lateinit for local variables is available since Kotlin 1.2.