Search code examples
androidkotlinanko

How to prevent a dialog (alert) from closing when you touch outside or press back using Anko


I'm ussing kotlin and anko for creating an alert/dialog (code below), but when you tap outside or press back it closes.

Here is the code

alert("TITLE") {
    title("Text")
    positiveButton("Ok") { action() }
}.show()

Here is how the solution will be in java (without ussing anko too)

dialog.setCancelable(false); // for prevent on back pressed
dialog.setCanceledOnTouchOutside(false); // for prevent on touching outside

Any ideas on how to achieve this using kotlin and anko? Thanks :)


Solution

  • Anko library of kotlin, provides the functionality to prevent dialog to close when press outside the dialog.. There is cancellable(BOOLEAN) method of alert to provide this functionality.

    I have used the below lines of code to stop alert dialog to close.

    alert("Testing alerts") {
                    title("Alert")
                    cancellable(false)  ////SET TRUE/FALSE ACCORDING TO URS REQUIREMENT
                    positiveButton {
                       ///PERFORM ANY TASK HERE
                        dismiss()
                    }
                    negativeButton {
                        dismiss()
                    }
                }.show()