Dialogs and alerts on Android using Anko and Kotlin

Dialogs and alerts on Android using Anko and Kotlin

To provide a good experience for users of your apps you have to inform them of certain things to know what is happening.

A good way to do this is to use alerts and dialogs, and Kotlin along with Anko will help you in this task.

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.

Alerts in Kotlin with Anko

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

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

This results in an alert like this:

alert-anko-kotlin

You can customize the actions by using the positiveButtonnegativeButton and neutralButton methods:

alert-anko-kotlin-2

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

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:

The result of the previous line will be this:

lert-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.

Meanwhile, I’d love to see if / where you’re using Kotlin, so please drop me a comment or leave a response if you have anything to share (or even any questions to ask!)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.