· 2 min read

Dialogs and alerts on Android using Anko and Kotlin (KAD 24)

Creating alerts and dialogs on Android is a relatively simple task thanks to the builder, but due to the verbosity of the language it usually becomes something quite illegible.

In Kotlin, by the mere fact of the lambdas, it simplifies us a little to understand what is happening in that code.

But thanks to Anko, we can make all this even easier, and in this article we’ll see how.

If you want to start today, I recommend you take a look at my free training, where you will have an hour and a half of content to know what are your next steps to become an expert in Kotlin.

image

Alerts in Kotlin with Anko

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

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

Within the block, you can specify some things like the title of the alert, or the buttons that you want to appear:

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

This results in an alert like this:

alert-anko-kotlin

You can customize the actions by using the positiveButton, negativeButton and neutralButton methods:

alert("Testing alerts") {
    title = "Alert"
    positiveButton("Cool") { toast("Yess!!!") }
    negativeButton("Never Ever") { }
    neutralButton("I'll think about it")
}.show()

alert-anko-kotlin-2

And even add a custom view that, of course, you can create also with Anko:

alert {
    title = "Alert"
    positiveButton("Cool") { toast("Yess!!!") }
    customView {
        linearLayout {
            textView("I'm a text")
            button("I'm a button")
            padding = dip(16)
        }
    }
}.show()

alert-anko-kotlin-3

Progress Dialogs

Another interesting feature that includes Anko is to create progress dialogs, and indeterminate progress.

To give an example of the second ones, you can create a progress dialog in this simple way:

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

The result of the previous line will be this:

alert-anko-kotlin-4

Conclusion

You see that thanks to Anko and the power of Kotlin, you can create small DSLs to simplify tasks. Ideally you could create DSLs on any part of the framework so that it makes interaction with it much easier.

In a later article we’ll see how to deal with SQLite databases.

Cheer up and come to my free training. I will tell you everything you need to learn about how to create your own Android Apps in Kotlin from scratch. Discover everything about the language of the future.

    Share:
    Back to Blog