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.

Alerts in Kotlin with Anko

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()

Progress Dialogs

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()

Conclusion

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

--

--

Developer Relations: Working at the intersection of engineering, marketing and community management • @beacamphq @bunzzdev

Love podcasts or audiobooks? Learn on the go with our new app.

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Trust Onyekwere

Developer Relations: Working at the intersection of engineering, marketing and community management • @beacamphq @bunzzdev