Dialogs and alerts on Android using Anko and Kotlin

In Kotlin, by the mere fact of the lambdas, creating alerts and dialogs on Android is relatively simple thanks to the builder. But thanks to Anko, we can make all this even easier, and in this article we’ll see how.

Writing alerts with Anko is pretty easy. Just create an alert block:

alert("Testing alerts") {
...
}.show()

You can also add some things like the title of the alert, or the buttons that you want to appear:

alert("Testing alerts") {
title = "Alert"
yesButton { toast("Yes!") }
noButton { }
}.show()

You can customize the actions even more by using the positiveButton, negativeButton and neutralButton methods as shown below:

alert("Testing alerts") {
title = "Alert"
positiveButton("Cool") { toast("Yes!") }
negativeButton("No") { }
neutralButton("Maybe")
}.show()

How about a customs view? of course, you can create that also with Anko:

alert {
title = "Alert"
positiveButton("Cool") { toast("Yes!") }
customView {
linearLayout {
textView("this is a text")
button("this is a button")
padding = dip(16)
}
}
}.show()

Another interesting feature that includes Anko is simplifying the creation of progress dialogs, and indeterminate progress.

you can create a progress dialog in this simple way:

indeterminateProgressDialog("This a progress dialog").show()

Kotlin really simplifies Android development as we did see from the code snippet above.

I help individuals and business owners take the leap into the world of digital transformation | Building @rad5academy

I help individuals and business owners take the leap into the world of digital transformation | Building @rad5academy