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
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

More Gems of Android Core KTX

You’ve just scratched the surface in this tutorial on the power of Core KTX! This section discusses a few more features of the library.

Collection Extensions on ViewGroup

Core KTX added many goodies to the ViewGroup class to make it more like a collection. This makes a lot of sense because all ViewGroup children like FrameLayout, LinearLayout, RelativeLayout, and others are containers that have their own children views.

Some examples of the collection extensions for ViewGroup in Core KTX are seen in the following function:

fun example(context: Context) {
  val viewGroup = LinearLayout(context)

  val view1 = View(context)
  val view2 = View(context)

  //1 Adding children
  viewGroup += view1
  viewGroup += view2

  //2 
  viewGroup[0] // Will return view1
  viewGroup[1] // Will return view2

  //3 
  view1 in viewGroup // Will return true
  view2 !in viewGroup // Will return false

  //4 
  viewGroup.size // Will return 2

  //5 
  viewGroup.isEmpty() //Will return false
  viewGroup.isNotEmpty() //Will return true

  //6 
  viewGroup.forEach {
    // the variable it will has the actual view index

  }
  viewGroup.forEachIndexed { index, view ->
    // the variable index contains the actual index and view has the actual view object
  }

  for (view in viewGroup) {
    // view is the actual view object
  }

  //7 
  viewGroup -= view1
  viewGroup -= view2

}

The above examples include the following collection-like actions on a ViewGroup:

  1. Adding children
  2. Accessing children using the get operator []
  3. Checking if an element is in the ViewGroup
  4. Checking number of child elements using size
  5. isEmpty() and isNotEmpty()
  6. Looping over children
  7. Removing elements

View

The View class also has useful Core KTX features, as shown in the following example:

import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible

fun example(context: Context) {
  val view = View(context)

  //1
  if (view.isVisible) // Boolean instead of Int
    view.isVisible = false // Instead of View.GONE
  else
    view.isVisible = true // Instead of View.VISIBLE

  if (view.isInvisible) // Boolean instead of Int
    view.isInvisible = false // Instead of View.INVISIBLE
  else
    view.isInvisible = true // Instead of View.VISIBLE

  if (view.isGone) // Boolean instead of Int
    view.isGone = false // Instead of View.GONE
  else
    view.isGone = true // Instead of View.VISIBLE


  //2
  view.updatePadding(
      left = 0, top = 0,
      right = 0, bottom = 0
  )

  view.updatePadding(left = 0) //Just update the left and the others are default values

}

The possibilities for View using Core KTX include:

  1. Checking visibility
  2. Updating padding

Uri

The Uri class has some nice additions in Core KTX:

import androidx.core.net.toFile
import androidx.core.net.toUri

fun example() {

  val string = "https://test.example.com/foo?bar#baz"

  // 1
  val uri = string.toUri() // Uri object from String

  // 2
  val fileFromUri = uri.toFile() // File object from Uri object

  // 3
  val uriFromFile =  fileFromUri.toUri() // Uri object from File object

}

You have helpers to:

  1. Convert a String to a Uri
  2. Get a File object from a Uri

SharedPreferences

Getting an Editor for SharedPreferences can be a pain, and often you might forget to call apply() to persist the changes:

Core KTX has you covered:

import androidx.core.content.edit

fun example(context: Context) {

  val preferences = context.getSharedPreferences("prefs", 0)

  //1
  preferences.edit(commit = true) {
    putString("key1", "value")
    putInt("key2", 1)
  } //2

  //1
  preferences.edit {
    putString("key1", "value")
    putInt("key2", 1)
  } //2
  
}

For SharedPreferences, Core KTX offers:

  1. Calling edit() to get an Editor
  2. Not needing to call apply(), since Core KTX does it for you

Anko vs. KTX

Anko is a Kotlin library from JetBrains. It shares the goals with Android KTX of making your life as an Android developer easier and making your code more readable and pleasant to use. Android KTX and are Anko are similar but not quite the same.

Differences Between Anko and Android KTX

They have common goals but with different scopes in mind. The mission of KTX is to bring idiomatic APIs to Kotlin users. As is mentioned in the repository, KTX does not intend to add new functionality to the existing Android APIs.

Anko has a wider scope, and this gives it the flexibility to innovate and create new features (Anko Layouts and Anko Coroutines are examples).

Deciding When to Use Anko or Android KTX

Generally speaking, Anko and Android KTX cover different parts of the Android API, and there’s no reason you can’t use both in your project. Investigate each one individually and use either as much as you want in your projects!

Where to Go From Here?

You can download the final project with all the Android KTX changes using the Download Materials button at the top and bottom of the tutorial.

Now that you’ve gotten started with Core KTX, you should check out other parts of Android KTX, including its use for Fragments, Palette, SQLite, and Navigation.

I also suggest you to check out some other resources:

Remember that Core KTX is an open-source project and you can contribute to it in many ways: proposing new features, reporting bugs or submitting a pull request.

I hope you enjoyed this introduction to Android KTX. If you have any comments or questions, please join in on the forum discussion below.