Android KTX Tutorial: Getting Started

In this tutorial, you’ll learn how to use Core KTX to make your code more concise and readable by refactoring an app that generates delightful collages. By Arturo Mejia.

Leave a rating/review
Download materials
Save for later
Share

Android KTX is one of the new kids in the Android Jetpack family. It’s a collection of Kotlin extension functions that will beautify and give a Kotlin-ish touch to existing Android APIs. KTX takes advantage of many of the awesome features in the Kotlin language to make all the old and rusty Java Android APIs feel like brand new.

Android KTX is an effort by the Google Android team to make the Android APIs more pleasant, idiomatic and easy to use for Kotlin developers, without adding any new features to the existing Android APIs. In this journey, you’re going to explore the APIs that Android KTX has to offer you

Why Is Android KTX Useful?

Android KTX simplifies your interaction with Android APIs by using features of the Kotlin language like extension functions, lambdas, and named and default parameters.

As an example, did you know that the class TextUtils has the methods isDigitsOnly and getTrimmedLength? Android KTX helps you discover many features on the Android APIs like these that you did not previously know existed because they were buried under tons of utility classes or static methods. Just by writing a dot after any object, you can now have a concise list of all the operations that you can apply to it, without having to memorize the methods in utility classes or make constant searches on Stack Overflow. This way, you can stand on the shoulders of giants and avoid code duplication.

Android KTX Packages

The KTX toolset is broken up into a number of different packages, so that you can import only the ones you need into your app project:

  • Core KTX: for use with framework APIs such as Toasts, Spans, and Menus
  • Fragment KTX: simplifies Fragment transactions
  • Palette KTX: for working with color palette APIs
  • SQLite KTX: simplifies SQLite database transactions
  • Collections KTX: for use with collection APIs
  • Navigation KTX: for use with Jetpack Navigation

In this tutorial, you’ll focus on the APIs that are wrapped by Core KTX.

Core KTX covers the Android framework APIs that are not tied to a specific component like fragments or SQLite. The following is a list of the packages included in core KTX:

Note: This tutorial assumes you have previous experience with Kotlin and Android. If you are unfamiliar with the language, have a look at this tutorial. If you’re just beginning with Android, check out some of our Getting Started and other Android tutorials.

Getting Started

Collage Droid is the app that you will use to use to see Core KTX in action — it’s an app that generates delightful photo collages. Along the way, you’re going to update it to take advantage of Core KTX goodies.

Download the Collage Droid project using the Download Materials button at the top or bottom of the tutorial. Open the starter project by using Android Studio 3.1.3 or later and selecting Open an existing Android Studio project:

Open an existing Android Studio project

Before going on with the tutorial, take a look at the existing starter code.

Collage Droid Structure

The Kotlin source code packages in the starter project appear as follows:

The Kotlin source files are:

  • MainActivity.kt
    This is the entry point of the app.
  • CollageFragment.kt
    This fragment is in charge of loading each photo template depending on which tab you selected.
  • TemplateType.kt
    An enum class that holds information related to every specific template; like the aspect ratio of the photos and which droid image should be presented by every template.

Now you have x-ray vision into how Collage Droid is structured!

Understanding Key Kotlin Features

Before you get started adding Core KTX code into the starter project, it’s worthwhile to look at how KTX works under the hood.

To enhance the Android APIs, Android KTX takes advantage of many awesome Kotlin features, like extension functions, operator overloading and destructuring declarations.

Note: If some of these topics are unfamiliar to you, take a look at the next few optional sections, which are denoted as “Optional” in the headers. If you are familiar with concepts, then feel free the skip these sections.

Extension Functions Fundamentals (Optional)

Extension functions allow you to add new functionality to an existing class, even without having access to the original class definition or source code.

For example, you already know that the class TextUtils has the method isDigitsOnly. To use it, you have to do something like this:

import android.text.TextUtils

fun test() {
  if (TextUtils.isDigitsOnly("123")) {
    //Do something
  }
}

But it makes more sense if the class String has this method itself, and you can then use it with any String instance, instead of having to call a static TextUtils method, like this:

fun test() {
  if ("123".isDigitsOnly()) { // Much nicer :]
    //Do something
  }
}

How can you achieve that? This is exactly what an extension function does. In another part of your code you define an extension function for the String class:

import android.text.TextUtils

//(1)  (2)   (3)
fun String.isDigitsOnly(): Boolean {
  return TextUtils.isDigitsOnly(this)
}

The following is going on in the extension function definition:

  1. The fun keyword.
  2. Name of the class to add the extension to followed by the dot(.) notation.
  3. The name of your new extension function.
Note: Inside the extension function, this is a reference to the caller object:
"1".isDigitsOnly() // this represents the String instance "1"
"1".isDigitsOnly() // this represents the String instance "1"

You can use an extension function by importing the file in which the extension function is defined.

Operator Overloading (Optional)

Did you know that in Kotlin you can change the behavior of common operators like +, * , [], and more?

Take a look at some niceties that Core KTX offers for you in the Menu class:

import android.view.Menu
import androidx.core.view.get
import androidx.core.view.minusAssign

fun myFunction(menu : Menu) {
  val firstMenuItem = menu[0] //Gets the first menu item.
  menu -= firstMenuItem // Removes the menu item from the menu object.
}

You’re able to use index notation on menu items and use the subtraction assignment operator right on the menu items themselves!

Behind the scenes, this operator overloading is occurring thanks to operator extension functions on the menu class:

import android.view.MenuItem

operator fun Menu.minusAssign(item: MenuItem) {
  return removeItem(item.itemId)
}

operator fun  Menu.get(index: Int): MenuItem {
  return getItem(index)
}

The only difference here is that you have to add the operator keyword before the fun keyword.