android domain KTX Tech Tools & Libraries tutorial

Android KTX Tutorial: Getting Started

Android KTX Tutorial: Getting Started

Android KTX Tutorial: Getting Started

Android KTX is among the new youngsters within the Android Jetpack household It’s a set of Kotlin extension features that may beautify and provides a Kotlin-ish contact to present Android APIs. KTX takes benefit of most of the superior options within the Kotlin language to make all of the previous and rusty Java Android APIs really feel like model new.

Android KTX is an effort by the Google Android group to make the Android APIs extra nice, idiomatic and straightforward to make use of for Kotlin builders, with out including any new options to the prevailing Android APIs. On this journey, you’re going to discover the APIs that Android KTX has to give you

Why Is Android KTX Helpful?

Android KTX simplifies your interplay with Android APIs through the use of options of the Kotlin language like extension features, lambdas, and named and default parameters.

For instance, do you know that the category TextUtils has the strategies isDigitsOnly and getTrimmedLength? Android KTX helps you uncover many options on the Android APIs like these that you simply didn’t beforehand know existed as a result of they have been buried underneath tons of utility courses or static strategies. Simply by writing a dot after any object, now you can have a concise record of all of the operations that you could apply to it, with out having to memorize the strategies in utility courses or make fixed searches on Stack Overflow. This manner, you’ll be able to stand on the shoulders of giants and keep away from code duplication.

Android KTX Packages

The KTX toolset is damaged up into various totally different packages, as a way to import solely those you want into your app challenge:

  • Core KTX: to be used with framework APIs similar to Toasts, Spans, and Menus
  • Fragment KTX: simplifies Fragment transactions
  • Palette KTX: for working with shade palette APIs
  • SQLite KTX: simplifies SQLite database transactions
  • Collections KTX: to be used with assortment APIs
  • Navigation KTX: to be used with Jetpack Navigation

On this tutorial, you’ll concentrate on the APIs which might be wrapped by Core KTX.

Core KTX covers the Android framework APIs that aren’t tied to a selected element like fragments or SQLite. The next is an inventory of the packages included in core KTX:

Observe: This tutorial assumes you’ve earlier expertise with Kotlin and Android. In case you are unfamiliar with the language, take a look at this tutorial. When you’re simply starting with Android, take a look at a few of our Getting Started and different Android tutorials.

Getting Started

Collage Droid is the app that you’ll use to make use of to see Core KTX in motion — it’s an app that generates pleasant photograph collages. Alongside the best way, you’re going to replace it to benefit from Core KTX goodies.

Obtain the Collage Droid undertaking utilizing the Obtain Supplies button on the prime or backside of the tutorial. Open the starter undertaking through the use of Android Studio three.1.three or later and choosing Open an present Android Studio venture:

Open an existing Android Studio project

Earlier than happening with the tutorial, check out the prevailing starter code.

Collage Droid Construction

The Kotlin supply code packages within the starter undertaking seem as follows:

The Kotlin supply information are:

  • MainActivity.kt
    That is the entry level of the app.
  • CollageFragment.kt
    This fragment is in control of loading every photograph template relying on which tab you chose.
  • TemplateType.kt
    An enum class that holds info associated to each particular template; just like the facet ratio of the photographs and which droid picture ought to be introduced by each template.

Now you’ve gotten x-ray imaginative and prescient into how Collage Droid is structured!

Understanding Key Kotlin Options

Earlier than you get began including Core KTX code into the starter challenge, it’s worthwhile to take a look at how KTX works underneath the hood.

To reinforce the Android APIs, Android KTX takes benefit of many superior Kotlin options, like extension features, operator overloading and destructuring declarations.

Observe: If a few of these subjects are unfamiliar to you, check out the subsequent few non-compulsory sections, that are denoted as “Optional” within the headers. In case you are acquainted with ideas, then be happy the skip these sections.

Extension Features Fundamentals (Optionally available)

Extension features permit you to add new performance to an present class, even with out accessing the unique class definition or supply code.

For instance, you already know that the category TextUtils has the tactic isDigitsOnly. To make use of it, it’s a must to do one thing like this:

import android.textual content.TextUtils

enjoyable check()
if (TextUtils.isDigitsOnly(“123”))
//Do one thing

However it makes extra sense if the category String has this technique itself, and you may then use it with any String occasion, as an alternative of getting to name a static TextUtils technique, like this:

enjoyable check()
if (“123”.isDigitsOnly()) // A lot nicer :]
//Do one thing

How are you going to obtain that? That is precisely what an extension perform does. In one other a part of your code you outline an extension perform for the String class:

import android.textual content.TextUtils

//(1) (2) (three)
enjoyable String.isDigitsOnly(): Boolean
return TextUtils.isDigitsOnly(this)

The next is occurring within the extension perform definition:

  1. The enjoyable key phrase.
  2. Identify of the category so as to add the extension to adopted by the dot(.) notation.
  3. The identify of your new extension perform.
Notice: Contained in the extension perform, this can be a reference to the caller object:

“1”.isDigitsOnly() // this represents the String occasion “1”

You need to use an extension perform by importing the file during which the extension perform is outlined.

Operator Overloading (Non-compulsory)

Do you know that in Kotlin you’ll be able to change the conduct of widespread operators like +, * , [], and extra?

Check out some niceties that Core KTX provides for you within the Menu class:

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

enjoyable myFunction(menu : Menu)
val firstMenuItem = menu[0] //Will get the primary menu merchandise.
menu -= firstMenuItem // Removes the menu merchandise from the menu object.

You’re in a position to make use of index notation on menu gadgets and use the subtraction task operator proper on the menu gadgets themselves!

Behind the scenes, this operator overloading is happening because of operator extension features on the menu class:

import android.view.MenuItem

operator enjoyable Menu.minusAssign(merchandise: MenuItem)
return removeItem(merchandise.itemId)

operator enjoyable Menu.get(index: Int): MenuItem
return getItem(index)

The one distinction right here is that it’s a must to add the operator key phrase earlier than the enjoyable key phrase.

Destructuring Declarations (Elective)

Destructuring is a shortcut function that lets you break down an object into a number of variables and declare them in only one step.

For instance, the Location class is primarily made up of two major variables latitude and longitude. Utilizing destructuring declarations from Core KTX you’ll be able to entry the latitude and longitude as follows:

import androidx.core.location.component1
import androidx.core.location.component2

enjoyable myFunction(location: Location)
val (lat, lon) = location

You assign (lat, lon) to the Location occasion, and Kotlin extracts the elements of the situation for you.

Behind the scenes, that is as soon as once more working because of extension features:

package deal androidx.core.location

import android.location.Location

inline operator enjoyable Location.component1() = this.latitude

inline operator enjoyable Location.component2() = this.longitude

The Location class has to operator extension features component1() and component2() that allow you to break the Location occasion into elements.

The inline key phrase is an optimization function. If you need study extra check out right here.

Sufficient with the idea! It’s time so that you can begin exploring Core KTX! :]

Android KTX

Setting Up Android Core KTX

You’ll enhance Collage Droid by including Core KTX!

To set it up within the undertaking, you solely want to incorporate the Gradle dependency. Open the app module construct.gradle file and add this line to your dependencies:

implementation “androidx.core:core-ktx:$androidx_version”

Core KTX is a part of Android Jetpack, which is specified utilizing an androidx dependency.

Word: As of the writing of this tutorial, the newest model of AndroidX is 1.Zero.Zero-beta01. You will discover the final model of Android Core KTX right here. Every new launch comes with launch notes for what has modified because the final model.

Additionally, remember that to make use of the 1.Zero.Zero-beta01 model, you have to goal Android API Degree 28 and migrate all of your help library dependencies to AndroidX. When you simply need to attempt Core KTX with out migrating, you need to use model Zero.three as an alternative.

Click on “Sync Now” to sync your Gradle information.

Superior! Now you need to use Core KTX in your undertaking.

Enhancing Collage Droid

In Collage Droid, each time you faucet a tab, the photograph template modifications; you do that by passing a Bundle object with the kind of template that you simply need to current.


bundleOf is a Core KTX helper perform that allows you to create a Bundle object from anyplace.

Within the CollageFragment.kt file, discover the newInstance() perform and exchange it with this equal utilizing bundleOf:

enjoyable newInstance(templateType: TemplateType): CollageFragment
val fragment = CollageFragment()

val bundle = bundleOf(ARG_TEMPLATE_TYPE to templateType.identify)

fragment.arguments = bundle
return fragment

You could have to press Choice+Return on Mac or Alt+Enter on PC to tug within the perform import.

This how the code appeared earlier than:

enjoyable newInstance(templateType: TemplateType): CollageFragment
val fragment = CollageFragment()

val bundle = Bundle()
bundle.putString(ARG_TEMPLATE_TYPE, templateType.identify)

fragment.arguments = bundle
return fragment

Utilizing bundleOf(), you keep away from needing to first create a Bundle object after which making a number of put calls so as to add knowledge into the Bundle. As an alternative, with Core KTX you cross one or many key/worth arguments as Kotlin Pair objects utilizing the to infix perform into bundleOf() all of sudden.

So Core KTX has made your code extra concise and readable with simply this primary easy change!


drawToBitmap() is an extension perform on the View class. It converts a view to a Bitmap object; this can be fairly useful for creating the collages.

Within the app, when you have got accomplished all of the picture buckets, a examine mark menu seems to allow you to generate a collage; you possibly can enhance the perform that’s answerable for that.

In CollageFragment, discover the perform viewToBitmap() and exchange it with the KTX model:

personal enjoyable viewToBitmap(view: View): Bitmap
return view.drawToBitmap()

Right here is the code previous to switching to KTX:

personal enjoyable viewToBitmap(view: View): Bitmap
// 1 Create a brand new bitmap with the view information
val bitmap = Bitmap.createBitmap(view.width, view.peak,
// 2 Draw the view pixes into the bitmap
val canvas = Canvas(bitmap)
return bitmap

Utilizing Core KTX, you killed the boilerplate Bitmap creation code and targeted on the primary aim.


Content material suppliers are excellent for sharing knowledge between apps. After the app creates the collage, it shops it within the image listing. To try this it makes use of a ContentValues object to share the metadata of the photograph collage with different apps.

You should use the Core KTX contentValuesOf() perform to create ContentValues objects in a simple and compact means.


In CollageFragment, discover the perform addImageToGallery and replace it with the Core KTX model:

personal enjoyable addImageToGallery(cr: ContentResolver, imgType: String, filepath: File): Uri?
val currentTime = System.currentTimeMillis()
val fileString = filepath.toString()

val values = contentValuesOf(
MIME_TYPE to “image/$imgType”,
DATE_ADDED to currentTime,
DATE_TAKEN to currentTime,
DATA to fileString
return cr.insert(EXTERNAL_CONTENT_URI, values)

With out Core KTX, the code appeared as follows:

personal enjoyable addImageToGallery(cr: ContentResolver, imgType: String, filepath: File): Uri?
val values = ContentValues()
val currentTime = System.currentTimeMillis()
val fileString = filepath.toString()

values.put(MIME_TYPE, “image/$imgType”)
values.put(DATE_ADDED, currentTime)
values.put(DATE_TAKEN, currentTime)
values.put(DATA, fileString)
return cr.insert(EXTERNAL_CONTENT_URI, values)

The contentValuesOf() perform has an identical syntax to bundleOf(). You move the metadata values as pair objects slightly than having to make a bunch of calls to place() features.

Getting [] Operator on Menu

As you noticed in one of many elective sections above, Kotlin allows you to add new conduct to operators. In Core KTX, the Menu class has prolonged the get operator to offer you an array-like syntax to entry the menu parts.

In Collage Droid, when you’ve crammed in all of the picture buckets on a tab, the examine mark menu choice is made seen.

In CollageFragment, seek for the perform hideMenuItemDone() and replace it to a Core KTX model:

personal enjoyable hideMenuItemDone(menu: Menu)
menuDone = menu[0]
menuDone.isVisible = false

Right here is the code with out Core KTX:

personal enjoyable hideMenuItemDone(menu: Menu)
menuDone = menu.getItem(Zero)
menuDone.isVisible = false

As you’ll be able to see, the Core KTX model takes full benefit of the Kotlin operator-overloading function. It’s not an enormous change to modify from utilizing the getItem() technique, however it makes your code somewhat extra concise and readable.

Collage Droid is now utterly utilizing Core KTX!

Extra Gems of Android Core KTX

You’ve simply scratched the floor on this tutorial on the facility of Core KTX! This part discusses a number of extra options of the library.

Assortment Extensions on ViewGroup

Core KTX added many goodies to the ViewGroup class to make it extra like a set. This makes a whole lot of sense as a result of all ViewGroup youngsters like FrameLayout, LinearLayout, RelativeLayout, and others are containers which have their very own youngsters views.

Some examples of the gathering extensions for ViewGroup in Core KTX are seen within the following perform:

enjoyable instance(context: Context)
val viewGroup = LinearLayout(context)

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

//1 Including youngsters
viewGroup += view1
viewGroup += view2

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

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

viewGroup.measurement // Will return 2

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

// the variable it should has the precise view index

viewGroup.forEachIndexed index, view ->
// the variable index incorporates the precise index and think about has the precise view object

for (view in viewGroup)
// view is the precise view object

viewGroup -= view1
viewGroup -= view2

The above examples embrace the next collection-like actions on a ViewGroup:

  1. Including youngsters
  2. Accessing youngsters utilizing the get operator []
  3. Checking if a component is within the ViewGroup
  4. Checking variety of youngster parts utilizing measurement
  5. isEmpty() and isNotEmpty()
  6. Looping over youngsters
  7. Eradicating parts


The View class additionally has helpful Core KTX options, as proven within the following instance:

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

enjoyable instance(context: Context)
val view = View(context)

if (view.isVisible) // Boolean as an alternative of Int
view.isVisible = false // As an alternative of View.GONE
view.isVisible = true // As an alternative of View.VISIBLE

if (view.isInvisible) // Boolean as an alternative of Int
view.isInvisible = false // As an alternative of View.INVISIBLE
view.isInvisible = true // As an alternative of View.VISIBLE

if (view.isGone) // Boolean as an alternative of Int
view.isGone = false // As an alternative of View.GONE
view.isGone = true // As an alternative of View.VISIBLE

left = Zero, prime = Zero,
proper = Zero, backside = Zero

view.updatePadding(left = Zero) //Simply replace the left and the others are default values

The chances for View utilizing Core KTX embrace:

  1. Checking visibility
  2. Updating padding


The Uri class has some good additions in Core KTX:

import androidx.core.internet.toFile
import androidx.core.internet.toUri

enjoyable instance()

val string = “”

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

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

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

You might have helpers to:

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


Getting an Editor for SharedPreferences is usually a ache, and sometimes you may overlook to name apply() to persist the modifications:

Core KTX has you coated:

import androidx.core.content material.edit

enjoyable instance(context: Context)

val preferences = context.getSharedPreferences(“prefs”, Zero)

preferences.edit(commit = true)
putString(“key1”, “value”)
putInt(“key2”, 1)

putString(“key1”, “value”)
putInt(“key2”, 1)

For SharedPreferences, Core KTX provides:

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

Anko vs. KTX

Anko is a Kotlin library from JetBrains. It shares the objectives with Android KTX of creating your life as an Android developer simpler and making your code extra readable and nice to make use of. Android KTX and are Anko are comparable however not fairly the identical.

Variations Between Anko and Android KTX

They’ve widespread objectives however with totally different scopes in thoughts. The mission of KTX is to deliver idiomatic APIs to Kotlin customers. As is talked about within the repository, KTX doesn’t intend so as to add new performance to the prevailing Android APIs.

Anko has a wider scope, and this provides it the pliability to innovate and create new options (Anko Layouts and Anko Coroutines are examples).

Deciding When to Use Anko or Android KTX

Usually talking, Anko and Android KTX cowl totally different elements of the Android API, and there’s no cause you possibly can’t use each in your undertaking. Examine every one individually and use both as a lot as you need in your tasks!

The place to Go From Right here?

You’ll be able to obtain the ultimate venture with all of the Android KTX modifications utilizing the Obtain Supplies button on the prime and backside of the tutorial.

Now that you simply’ve gotten began with Core KTX, it is best to take a look at different elements of Android KTX, together with its use for Fragments, Palette, SQLite, and Navigation.

I additionally recommend you to take a look at another assets:

Keep in mind that Core KTX is an open-source challenge and you may contribute to it in some ways: proposing new options, reporting bugs or submitting a pull request.

I hope you loved this introduction to Android KTX. If in case you have any feedback or questions, please take part on the discussion board dialogue under.

Obtain Supplies

(perform(d, s, id)
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); = id;
js.src = “//”;
fjs.parentNode.insertBefore(js, fjs);
(doc, ‘script’, ‘facebook-jssdk’));