Kotlin – Introduction to Anko for Android  (2/4) | eMan

Kotlin – Introduction to Anko for Android  (2/4)

We will show you a few tricks on how to make toasts and dialogs easier. We will also launch activities and get to other useful tips which can be found in the Anko library. This article builds on the first part where we have laid the foundation on which we will now build our demo application.

Previously in part 1, we got a quick introduction in how to start with Kotlin in the Android Studio and how to create and set up a new project.

Next, we got a general idea of what Anko is for and how to create a view (Anko Component).

In part 2, we will extend our knowledge of the Anko library. We will learn:

  • How to show toasts and dialogs
  • How to start a new activity
  • How to use useful functions which Anko provides, such as running it in a background thread and UI thread

List of all parts of the series:

1. Setting up the Android Studio, project, and creating your first view in Anko
2. Buttons, Toasts, Alert Dialogs, Intents, UI & Background Threads
3. View Enhancements
4. Fragments & RecyclerView


Button  – onClick Action and Toasts

We will go back to our SignInView and learn how to add the onClick action to a button. We will also learn how to read data from the EditText widget in Anko and how we can easily show a toast and later a dialog.

Let’s go back to our Sign-InView we created in the last article. Thanks to Kotlin and mainly to the Anko library, adding the onClick action to our button could not be easier.



If we create a UI using Anko DSL (directly in code instead of in XML), then our code could look much easier:



As you might have noticed, we used a different definition of the view of toast components in both cases. In the first case we view toast the classical Android way. In the second case we have used an extension function from the Anko library for viewing the toast. That means we do not have to deal with the regular mistake of forgetting to use the show() method. In both cases we view the toast with the time view set as “SHORT”. If we wish to view the “LONG” toast, then Anko offers the aptly named extension function:



Now let’s focus on the EditText for entering the username. After clicking on the Sign-In button, we view the toast which would include the text entered by the user into the username field.

First, we need to add a reference to our username:


Then we can add an onClick DSL block to our Sign-In button and view the text in the given toast:



Our code is now ready, so let’s try to run the application and test whether we have done everything right. If we have, then you should see something similar to the following picture (if you entered an Anko text):

Just for the final check, your code in the Sign-InView.kt should look like this:



Creating Sign-In Business Logic

Before we create our first business logic in connection to the Anko library article series, we need to prepare our domain objects first.

For the Sign-In process, we will create a new Kotlin file named DomainObjects.kt where all our POJO objects will be defined as data classes. Place this file into the new package named model (inside of the sign_in package). Then, create a first data class named AuthCredentials in this file and with these arguments:



Create a new package bl (or name it like you usually do for your business logic) and create a new interface ISignInBL.kt + implementation class SignInBL.kt.

Define a new function called checkUserCredentials in the ISignInBL.kt interface:



Now, implement this method in the SignInBL.kt where you can check the username and password. You will not implement any persistent layer (we will explain this in future Kotlin articles, specifically in the ones about the Requery library) for our demo project. Perform the check by letting the user through when they enter username = frosty and password = snowman.



Great, now we just implemented simple business logic for our sign-in process. Next step is to add getting the entered value from the username and password edit texts and checking them. That is for case that user would not fill those fields in your app. Then use the business logic to check the user access (using the checkUserCredentials function).

Checking The Sign-In Form

Now we will add a check of the entrance fields (username and password) in the Sign-In form. First, we need to keep a reference to our EditText’s widgets (we already did it for the username at the beginning of this article):



Next we need to create a new private function handleOnSignInButtonPressed with these arguments:

  • ui: AnkoContext
  • username: String
  • password: String

It will replace our “Hello” toast from the onClick DSL action in the Sign-In button:



Alert Dialog

Anko contains a DSL block for viewing dialogs:


Pretty easy, don’t you think?

Now we know how to show the Alert dialog in Anko so we can easily try this experience out in our demo application. We insert the code for viewing the dialog into the function handleOnSignInButtonPressed where we check whether the user credentials are correct and if they are filled in by the user.



If you checked the inserted code in more detail, you surely noticed that I use the isBlank() function. This function is to be found in the stdlib Kotlin library and its purpose is to check whether the inserted text is empty or whether it contains white characters. We also used the with{} expression where we placed the Alert dialog definition. The ui argument is here because we are defining the UI in the Anko widget and we need a reference for the context of this component for using the extension function from Anko.



Let’s run the application now and you should see the alert dialog if the username and/or password field is empty when the Sign-In button has been pressed:

Oops, I almost forgot to show the definition of new text strings:



How to Call Activity/Fragment From AnkoComponent

In a real application, I guess that most of you are using the MVP pattern or even the new Architecture Components introduced at Google I/O 17 to separate logic from the UI definition of activity/fragment to have cleaner code. We will not use any of those in our demo application, but if you are interested in one of the MVP frameworks called Mosby, you could take a look at my github project kotlin-anko-demo where I tried to connect Kotlin, Anko, Mosby, and other libraries.

For communication between Activities, Fragments, and others components, I use RxJava & RxKotlin via definition of RxBus. We will use only the communication between the Activity and UI via the Anko component from the related Activity in our demo.

If you remember from the first article, when you create AnkoComponent<T> you must define a generic type T as the component owner. Thanks to that we can access the Activity from the connected component, meaning from the owner. That means we can easily access the activity from our SignInView component by calling it e.g. ui.owner.someFunction(...).

Open the SignInActivity.kt class and add a new function with the name authorizeUser:



Let’s go back to the SignInView.kt where we left TODO in the else branch from the previous implementation. Inside the function handleOnSignInButtonPressed we call a new function, authorizeUser:



Now let’s come back to the SignInActivity.kt. There we will learn how we can run the code on the background thread easily by using the Anko library.


Asynchronous Tasks

All of you certainly know what kind of hell it is to use the asynchronous call in a standard Android SDK. The Anko library introduced a better way to use async:


Note: The examples are related to the 0.9 version. We can use Kotlin Courotines in newer versions of the library, but that is another topic for a different article.

If you need to put another function to async, then you can use the doAsyncResult(function_call_here) function:


We can even use our own instance of executor for executing the operation in the background:


So we just learnt about another great part of the Anko library, so let’s try it out.

In our SignInActivity, we need to check if the user who is trying to sign in with our app has the correct credentials in the Sign-In form. In a real application, we would have a user’s credentials stored in the database but in our case to make it simple, we will not deal with it in this article (Anko includes many extension methods for work with SQLite, but it is a topic for a different article). We can perform the check of user credentials in the background thread (async way):



In a code snippet above, we checked a user’s credentials in the background thread (the async way) and the result has been delivered back to the UI thread where toast will be shown, provided the credentials are correct. Otherwise, the Access Denied Alert dialog will appear.

Note: uiThread() acts quite differently for different classes. When called in Activity, code in lambda would not be executed if isFinishing() is true. Use ctx.uiThread { } if this is an unwanted result.

Full code of SignInActivity is supposed to be:



In the next step we will go back to the SignInView.kt, because we need to implement the showAccessDeniedAlertDialog function which we added to the activity in the previous step:



In this method I use the variable ankoContext, but where did it come from? It is a global variable with the definition of Anko context (previously known as ui: AnkoContext<SignInActivity>), so we can access it also from other functions:




In this section I would like to show you how Anko could be useful to make your life easier with some useful intent functions.


If you take a look into the source code of the Anko library, those functions are nothing else than extension functions:


So we now know we can use extension functions from Anko when working with intents. So let’s try it out in our first demo project. We will learn how to run the SignInActivity from the MainActivity class.

If we do not need to enter any flags or parameters when launching the activity, we can easily write:


If we need to set the parameters, our code would look like this without using the Anko library:


By using the extension functions from the Anko library, we can edit the code to make it look like this:

We will not set any flags or arguments in our demo application so our result code for MainActivity is as follows:



Summary of Part 2

In this article from a series about the Anko library we learnt how to show toasts and dialogs on Android. We also tried to define different actions/action listeners for UI components. It was mainly the onClick action added to the Sign-In button.

We also explained an interaction between the AnkoComponent (our SignInView) and Activity in a simple way and you learnt how to use async calls and run operations in the background.

In Part 3 we will come back to UI and play with it to improve it.

Vaclav Souhrada
Vaclav Souhrada
Kotlin & Android Developer at eMan, Czech Kotlin User Group Founder and Organizer


eMan a.s.
U Pergamenky 1145/12
170 00 Praha 7
Czech Republic

View map

+420 222 202 222


eMan Solutions LLC
The Cannon Houston
1334 Brittmoore Rd
Houston, TX 77043
United States of America
View map

+1 (346) 232 2867