Introduction to Anko for Android — Part 1

Vaclav Souhrada
12 min readMar 1, 2017

--

In this and future posts, I would like to give you a quick introduction to the Kotlin Anko DSL library.

Anko is a library that uses Kotlin and provides a lot of extension functions to make our Android development easier.

List of all parts:

Part 1

In this part 1, you will learn how to create a new Android project with Kotlin step-by-step, how to configure Gradle files to work with Kotlin and finally you will create your first basic view (Sign In) in Anko DSL library.

Note: We will add more logic to our Sign In function in part 2.

Import project from GitHub

A project which will be created by this series of posts you can download it from my GitHub repo here or you can follow post to create a complete project step-by-step.

Branches:

  • master -> complete project from parts 1–3
  • part 1, part 2, part 3, part 4
  • branch before-kotlin-activity contains a code before we made conversion Java to Kotlin — so you can try it yourself

Setting up Android project with Kotlin and Anko

First, we need to install Kotlin plugin for our Android Studio (Intellij). I’m using Android Studio 2.3 beta 4 on Mac OS. Go to preferences -> plugins -> Browse repositories and search for Kotlin:

Now are Android Studio is ready to have a fun with Kotlin :)

Let’s start with a creation a new project: (if you do not want to create it — just clone branch before-kotlin from Github)

Start a new Android project from a dialog or from menu File -> New -> New Project(depends if you are inside of another project or in a dialog which Intellij show if you are not inside of project).

Now you will be asking for a name, domain, and package. You can write what you want or just write what I used

If you want to edit a package name you can click on the edit button on right side and change it manually like I did it.

Now you will be asked to select version of Android API to target more devices we will select API 15

You can select now without Activity, but I would like to show you nice feature in IntelliJ / Android Studio how to convert existing Java code to Kotlin so for this example we will select an empty Activity. Name it like you want but I will let their MainActivity name.

After these steps, a new project structure of our new Android app should be created. You can check if you installed Kotlin correctly, for instance, go to File -> New and there you can see that you are able to create Kotlin Activity like on this picture:

Configure Gradle

In this section, I will show you how you can integrate Kotlin to your Android project. If you are integrating Kotlin to some existing bigger project I recommend to you do this integration manually because sometimes Kotlin Tool for this can make a mess into your Gradle files. But for new “empty” created a project I did not find any troubles or some mess after what I tried to use automated way so let’s go in this tutorial to use an automated tool (for a manual way just see what automated tool added below and do it in the same way).

The Kotlin plugin which we already installed to our Android Studio contains some tools which we can use to work with Kotlin.You can easily configure Kotlin in our projects.

If we now select an option Configure Kotlin in Project, the Kotlin plugin will configure our Gradle scripts for us or you can do it yourself which I prefer because you will know what you have in your Gradle files. Anyway, for our simple example, we will use this feature and let plugin does this work for us. It will configure Kotlin with stable version 1.1.

So select Configure Kotlin in Project. Now you will be asked to choose Configurator:

Select Android with Gradle -> ta-da … We should have Kotlin for Android in our projects.

First, we will describe root build.gradle

You can see that Kotlin plugin added definition to ext. part which version of Kotlin we are using 1.1.0 + added kotlin-gradle-plugin on the classpath.

Next check build.gradle file inside of the app module:

See line 2 where the gradlekotlin-android plugin is applied. Row 31 is where plugin added a dependency on the Kotlin Standard Library which relies on Java API version. Previously we used only kotlin-stdlib, now we should use jre7 or jre8 instead.

In next step, we will improve our Gradle files little bit.

Modify root build.gradle

  • add a version of support dependencies 25.1.1 (row 5)
  • add a version of Anko (0.9.1 in a time of writing this post) (row 6)

Final root Gradle file should be:

Now let’s go to modify build.gradle in the app module:

What has been changed:

  • row 15 — Jack enabled
  • row 25–28 — Java 8
  • row 40–41 — Added Anko dependencies

Of course, you can use kotlin-stdlib-jre7

Note: If you will use kotlin-stdlib-jre8, then jack option must be enabled but Instant Run will stop work in AS if jack is enabled.

You can see that we added a few Anko libraries. Anko is consist of small libraries. So that is great because you do not need to include a whole library if you need only some piece of code. For instance, if you want to use Anko library only for your work with the RecyclerView, so you can just include only: org.jetbrains.anko:anko-recyclerview-v7. Next what you need to do is add reference on a main library based on minSdkVersion of your project.

On the other hand, if you do not want to use DSL features which Anko provides you can just add org.jetbrains.anko:anko-common.

For more info about available libraries and which you need to use see an official description here.

After these steps, our project is ready to add some Kotlin code and finally to see how Anko is working and what can offer to us.

Convert Activity written in Java to Kotlin

Now it’s time to try some cool feature in Android Studio (AS). Open your MainActivity.java

I know you see nothing interesting — normal java code for Activity but now we will let AS to convert java code to Kotlin. In menu select Code -> Convert Java File to Kotlin File and ta-da

We have our first Activity written in Kotlin and project structure

Kotlin as a source folder

This step is optional. If you want to keep java as a source folder you can skip this step.

Note 1: If you will follow steps below so you will still see java folder as a source in the Android Project View because Android Studio merges all java sources to folder java.

Rename java foldersrc to kotlin (an optional step)

Now we must add sourceSets dsl block to our app/build.gradle :

android {
...
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
test.java.srcDirs += 'src/test/kotlin'
}
}

Now, look at your project structure.

In the Android Project View we have still java as source folder:

Switch to Project View and now you can see that we have kotlin source folder:

The issue is reported there: https://code.google.com/p/android/issues/detail?id=214919

Now try to run application only to be sure that everything is working:

Creating your first view with Anko

Take a look at activity_main.xml. You can see that generated view has a root layout android.support.constraint.ConstraintLayout .

Anko is a very powerful library but it is still under development and needs time to add a new feature so of course also in this library you can find bugs or missing parts which you want to use.

One of missing feature is support for Constraint Layout (https://github.com/Kotlin/anko/issues/210)

We can solve this that we will mix Anko view definition together with XML — but this is not our goal of this post where we want to see how to create a view in code by using Anko DSL. I will give you answer later on this topic. Because of this limitation, we will use LinearLayout.

We will create an application with 2 views:

  • Sign In
  • Say Hello to signed user

Sign In functionality

In this process, we will create the Sign In view with these widgets

  1. username (frosty)
  2. password (snowman)
  3. Sign In button

Username and password will be predefined (we do not have registration process).

Sign In Activity

To have a nice project structure I created a new package called sign_in . Now it's time to create a new Activity (do not forget to create it in Kotlin).

Click on sign_in package and select:

New -> Kotlin File / Class

or you can use a wizard to create a new Activity

New -> Kotlin Activity — Empty Activity:

with a name SignInActivity . Uncheck Generate Layout File check box because our view will be defined in code by using Anko DSL:

Your project structure should be now:

Anko Component

We can use Anko DSL directly inside of our Activity class but convenient to have UI in the separate class called Component. It allows for easy re-use and your code in your activity or fragment will be cleaner.

Now it’s time to create our first view inside of component and then set up our SignInActivity to create a view from our component. We will name it SignInView.

Add editText {}DSL block. Inside of this block we have now access to all attributes like we have in XML and of course to all methods which we can use from a code. As first we will set a unique id to our editTextwidget.
Wee need to create ids.xmlfile and define id(s) for our Anko widgets before we can use it in the code.

<!-- ids.xml --><?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="usernameEditText" type="id" />
</resources>

now we can finaly define id = R.id.username to our editText.

override fun createView(ui: AnkoContext<SignInActivity>) = with(ui) {
editText {
id = R.id.usernameEditText
}
}

Next add hintResource and textSize = 24f :

strings.xml

<resources>
<string name="app_name">Android Anko Sample</string>
<string name="sign_in_username">Username</string>
</resources>

Your code should looks like this:

override fun createView(ui: AnkoContext<SignInActivity>) = with(ui) {
editText {
id = R.id.usernameEditText
hintResource
= R.string.sign_in_username
textSize
= 24f
}
}

Note: if you want to (from some any other reason) use text directly instead of reference to strings.xml so you can use hint property in the editText.

A code which we were written looks very nice and clean do not you think? A code which we were written looks very nice and clean do not you think? BUT something is still missing … As I already mentioned we will use the LinearLayoutso our next goal is to wrap username to LinearLayout.

LinearLayout can have a vertical and horizontal position. This we can set by using orientation attribute. In Anko, we have directly a specific DSL block for vertical — verticalLayout .

override fun createView(ui: AnkoContext<SignInActivity>) = with(ui) {
verticalLayout {
editText {
id = R.id.usernameEditText
hintResource
= R.string.sign_in_username
textSize
= 24f
}
}
}

If you want to use LinearLayout with horizontal orientation you can write:

linearLayout {
orientation = LinearLayout.HORIZONTAL
}

In next step we define parameters for our verticalLayout and usernameEditText . In Anko this is done by using lparams function:

Note: In Anko, you specify LayoutParams right after a View description. This is recommended by official documentation, but you can see that it is also possible to define it inside of view, but with some limitations and drawbacks. You can read for instance this GitHub issue here.

In first version of this series about Anko I had all lparams inside of views without any troubles, but after hint what I got from David Bilik (thank you for hint David) I decided to do it in official way after that I read all troubles with this. however, I have lparams definition inside of root layout to avoid troubles with the return value. I do not see any troubles to use it inside of root layout.

Now it is a right time to try run our application and see if everything is working. Before we can run it we must finish last two steps:

  • say to activity that must use our view defined in the AnkoComponent
  • redirect our application flow from the MainActivity to SignInActivity.

Open SignInActivity. To define that our view must be create from our SignInView (AnkoComponent) is very easy. Just add to onCreate method this line of code (below super.onCreate(…) call):

To test if app is working just add definition to start SingInActivity from our MainActivity . In part 3, we will explain how can we use intents and how to start a new activity in an easier way thanks to Anko but for now just do it in a default Android way:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

startActivity(Intent(this, SignInActivity::class.java))
finish()
}

}

and run application:

Note: Please ignore how application is looking in this part 1 post. In future posts we will make it nicer.

Nice, our application is running and a view defined in the AnkoComponent (SingInView) is working too. Next please add an editText widget for a password.

editText {
id = R.id.passwordEditText
hintResource
= R.string.signIn_password
textSize
= 24f
}.lparams(width = matchParent, height = wrapContent)

We learned how to use editText widget. Now we will focus how to add a button. Thanks to Anko we have similar DSL block like for editText. Much more easier way how to add button is:

button("Sign In")

That’s cool — do not you think it same? Run app:

Ta-da our SignIn button is there :).

Of course, we should do it better so we must define an id of button, size parameters, and later action what happen if a user presses this button.

Final code our our SignView looks like:

Summary of Part 1

In this first post you learned, how to create a new Android project with Kotlin step-by-step, how to configure Gradle files to work with Kotlin and finally you created your first view (Sign In) in Anko DSL library.

In next post (part 2) we will add more logic to our Sign In process. You will learn how to work with threads, Intents, toasts, and dialogs by using the Anko library.

Thank you for reading and stay tuned.

--

--

Vaclav Souhrada

Android Developer | Kotlin enthusiast | Czech Kotlin User Group organizer (www.kotliners.cz)