Anko library

Share

Ever since Kotlin became an officially-supported language from Google and Android to this moment it’s amazing to see how much time and resources the Kotlin team has invested in developing some great and helpful tools to make Android development easier. In this article, I’ll show you how Anko library can make your life better. In addition, I will share different ways you can use Anko in your android development.

What is Anko?

Anko is a very robust library developed by JetBrains. Its main purpose is the generation of UI layouts by using code instead of XML. This is a fascinating feature I recommend you try out in your next app development. Anko includes a plethora of beneficial functions and properties that avoids lots of boilerplate. We will see several use cases throughout this article, but you will quickly see which kind of problems this library solves. Since Anko is a library written specifically for Android, I would recommend you to try first to understand how it works behind the scenes. Anko implementation is an excellent example to learn useful ways to get the most out of the Kotlin language. Before going any further, let’s use Anko to simplify some code. As you will see, anytime you use something from Anko, it will include an import with the name of the property or function to the file. This is because Anko uses extension functions to add new features to the Android framework. We’ll take a look at what an extension function is and how to write one.

Take, for instance, in ListActivity:onCreate, an Anko extension function can be used to simplify how to find the RecyclerView:

/*
val todoList : RecycleView = find(R.id.todo_list)
*/

Alert Dialogs

Anko provides a declarative way of creating alert dialogues with text messages, lists, progress bars and even with your own DSL layout.

Take, for instance, if you want to display an alert message to users with a couple of buttons at the bottom, all you need is:

/*
alert("Contact", "Do you want to call Aleksandar?") {
    positiveButton("Yes") { processToCall() }
    negativeButton("No") { }
}.show()
*/

There is a function that creates and shows a list dialog:

/*
val fruits = listOf("Apple", "Banana", "Peach")
selector("What is your favorite fruit?", fruits) { i ->
toast("So your fruit is ${fruits[i]}, right?")
}
*/

Both indeterminate and basic progress dialogs are supported:

/*
progressDialog("Please wait a minute.", "Downloading…")
indeterminateProgressDialog("Fetching the data…")
*/

I mentioned initially that you can create your own DSL layout in dialogs. This is how a custom layout is created:

/*
alert {
    customView {
        verticalLayout {
            val familyName = editText {
                hint = "Family name"
            }
            val firstName = editText {
                hint = "First name"
            }
            positiveButton("Register") {
                register(familyName.text, firstName.text)
            }
        }
    }
}.show()
*/

Intent Callers

In Android, every application has code that loads a page in the default web browser, launches a new email activity or call some from your contacts using intents, so there are helper functions for this in Anko:

/*
browse("http://somewebsite.org (http://kotlinlang.org/)")
email("admin@domain.net (admin@kotlin.net)", "Here I am!", "Hello World")
makeCall(number)
*/

Services

Android system services, such as WifiManager, LocationManager or Vibrator, are available in Anko through extension properties for the Context:

/*
if (!wifiManager.isWifiEnabled()) {
    vibrator.vibrate(200)
    toast("Wifi is disabled. Please turn on!")
}
*/

Intents

The common way of starting a new Activity is to create an Intent, maybe put some parameters into it, and finally pass the created Intent to the startActivity() method of a Context.

/*
val intent = Intent(this, javaClass<SomeActivity))
intent.putExtra("id", 1)
intent.putExtra("firstName", "Velimir")
startActivity(intent)
*/

As you see, with traditional approach there is four lines of code.

With Anko we can do this in exactly one line of code:

/* 
 startActivity("id" to 1, "firstName" to "Velimir") 
 */

startActivity() function accepts key-value pairs that will be passed as Intent extra parameters. Another function, startActivityForResult() with similar semantics is also available.

Setup Anko in your project

Adding Anko to your project is quite easy. You can add the following dependencies:

/*
ankoVersion = "0.10.1"
dependencies {
    compile "org.jetbrains.anko:anko-appcompat-v7-listeners:$ankoVersion"
    compile "org.jetbrains.anko:anko-design-listeners:$ankoVersion"
    compile "org.jetbrains.anko:anko-design:$ankoVersion"
    compile "org.jetbrains.anko:anko-sdk15-listeners:$ankoVersion"
    compile "org.jetbrains.anko:anko-sdk15:$ankoVersion"
}
*/

That’s all from me for now :). I hope that the understanding of Anko library is little bit clearer for you and that you will successfully use it making new Android apps.

Share

Sign in to get new blogs and news first:

Leave a Reply

Dušan Šećerov

Android Software Developer @Endava
mm

Dušan Šećerov has been working on some exciting projects, where he had a chance to improve his skills in mobile application development. He gained his first working experience in software development in small software company Egarno in Novi Sad. He worked there as Junior Android Developer.

He enjoys being occupied by interesting tasks where he can acquire new knowledge.

Sign in to get new blogs and news first.

Categories