Goddchen avatar

Android KTX - Android Kotlin Extension Functions

goddchen

Published: 06 Feb 2018 › Updated: 06 Feb 2018Android KTX - Android Kotlin Extension Functions

Android KTX - Android Kotlin Extension Functions

So, apparently Google has released a neat utility library for Android devs who use the Kotlin language.
It is basically a collection of utility functions that make common boilerplate code unnecessary.

How to start

So how do you start using the new library: simply include it as a dependency

repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:0.1'
}

Now you can use make use of all the cool utility functions.

Examples

ViewTreeObserver

Old way:

view.viewTreeObserver.addOnPreDrawListener(
    object : ViewTreeObserver.OnPreDrawListener {
        override fun onPreDraw(): Boolean {
            viewTreeObserver.removeOnPreDrawListener(this)
            actionToBeTriggered()
            return true
        }
    })

New way:

view.doOnPreDraw {
     actionToBeTriggered()
}

Writing shared prefs

Old way:

sharedPreferences.edit()
    .putBoolean("key", value)
    .apply()

New way:

sharedPreferences.edit {
    putBoolean("key", value)
}

Others

There are tons of new extension functions an more to come in the future. For a complete list of currently supported extension function look here: https://android.github.io/android-ktx/core-ktx/

Summary

I found some really useful extension functions in this new library that I will definitely use in the future (Context.systemService(), View.toBitmap(), ViewGroup.forEach(...), just to name a few).

If you got any questions or comments, let me know in the comments below. Also let me know if you want to read more #androiddev content on Steemit!

Leave Android KTX - Android Kotlin Extension Functions to:

Written by

Freelancer - Android Development

Read more #android posts


Best Posts From Goddchen

We have not curated any of goddchen's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Goddchen