Using Android Jetpack KTX (2024)

Using Android Jetpack KTX (3)

Android Jetpack KTX is an effort by the Google to make the Android APIs much more pleasant, idiomatic and easy to use for Kotlin developers. Moreover this process is lack of adding any new features to the existing Android APIs. As a matter of fact, Android KTX simplifies your interaction with Android APIs by using features of the Kotlin language, such as extension functions, lambdas, and named and default parameters. This essay aims to discuss Android KTX by providing some examples for Android developers.

Introduction and Overview

As we know, Android Jetpack is set of libraries, tools, and guidance for modern Android development. Now, there are four main categories for using Jetpack, which includes: Architecture, UI, Behavior, and Foundation. In other words, these best practices help developers for writing high quality Android apps easier, limiting boilerplate code, and simplifying complex tasks. As a result, you can be able to focus on the code that you really care about. Also, AndroidX is the package name for all libraries within Jetpack. Therefore, you can think of AndroidX as the open source project that you can be able to use to develop, test, version, and release Jetpack libraries. In fact, in I/O of 2018, Google has announced that they refactored the Support Library to the AndroidX namespaces. So, they did this similar task with Support Library 28. Also, they announced AndroidX 1.0. Basically, AndroidX is a considerable improvement to the original Android Support Library that is no longer maintained. AndroidX packages completely replace the Support Library by providing some new features and libraries.

Additionally, Android KTX is a set of extensions to the Android framework aims at making your development with Kotlin more clear, pleasant, and idiomatic. Android KTX provides an appropriate API layer on top of both Android framework and Support Library to make writing your Kotlin code much more natural. Google has had several releases including contributions from the community. They also changed the name to Core KTX as part of Jetpack, and it divided into modules. This set of libraries aimed at accelerating Android development. The core-ktx library contains extensions to the features and functionality of the framework. In other words, Android KTX has one core module and a few other modules, which are more domain-specific. Classes from AndroidX such as FragmentManager, Collection, LiveData reactive streams, and the new Navigation component have associated KTX artifacts. In addition, these extensions leverage several Kotlin language features as follows:

  1. Extension functions

2. Extension properties

3. Lambdas

4. Named parameters

5. Parameter default values

6. Coroutines

Android KTX is a set of Kotlin extensions that are included with Android Jetpack and other Android libraries. KTX extensions provide concise, idiomatic Kotlin to Jetpack, Android platform, and other APIs.

The following sections will consider some examples of how Android KTX could be helpful for writing more natural and concise Kotlin code.

Getting Started

Initially, to start using Android KTX in your Android Kotlin projects, you should add the following to your app module’s build.gradle file:

repositories {
google()
}

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

In fact, the Core KTX module provides extensions for common libraries, which are part of the Android framework. These libraries do not have Java-based dependencies that you require to add to build.gradle. Then, after syncing your Android project, the extensions appear automatically in the IDE’s auto-complete list. Therefore, selecting an extension automatically adds the necessary import statement to your file.

Considering some examples in using Android KTX

The KTX toolset is broken up into a number of different packages and modules. So, you can import only the ones you need into your Android 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 main section, some examples of how Android KTX will be considered.

Fragment KTX

The Fragment KTX module provides a number of extensions to simplify the fragment API. To include this module, you must add the following to your Android app’s build.gradle file:

dependencies {
implementation "androidx.fragment:fragment-ktx:1.2.5"
}

Without KTX, performing a fragment transaction requires starting a transaction, triggering an action like adding or replacing a fragment, and then deciding on one of the four commit methods based on whether the commit should be scheduled or called synchronously, allowing StateLoss or not. For example, the default usage could be like this:

supportFragmentManager .beginTransaction() .replace( R.id.my_fragment_container, myFragment, FRAGMENT_TAG ).commitAllowingStateLoss()

Fragment KTX adds the transaction extension function to the FragmentManager class, removing all the begin transaction and commit boilerplate, as well as providing default values for sync and StateLoss that you can easily overwrite. For instance:

supportFragmentManager.transaction( allowStateLoss = true ) { Replace( R.id.my_fragment_container, myFragment, FRAGMENT_TAG)
}

To avoid forgetting to call, you should display when you are showing a toast. Besides, to simplify the code, you should use the context extension function from core-ktx. For example:

context.toast(R.string.text)

SQLite KTX

For using the AndroidX supported SQLite database when implementing database transactions, you require quite a lot of boilerplate. By using SQLite KTX, you can be able to focus on the operations that you want to make in the database. Then, just only let the transaction method handle the rest. For instance, the default usage could be like this:

db.beginTransaction() try{ db.setTransactionSuccessful()} finally { db.endTransaction()}

So, for using SQLite KTX, you must mention transaction extension to perform a database transaction as follows:

db.transaction {
// insert data
}

However, to use this module, you have to add the exact dependency to your Android app’s build.gradle file as usual.

ViewModel KTX

As a matter of fact, the ViewModel KTX library supports a viewModelScope() function, which makes it more easier to launch coroutines from your ViewModel. The CoroutineScope is bound to Dispatchers.Main , and is automatically cancelled when the ViewModel is cleared. Thus, you can be able to use viewModelScope() instead of implementing a new scope for each ViewModel in your Android project. For instace, the following viewModelScope() function launches a coroutine, which makes a network request in a background thread. As a result, the library manages all of the setup and corresponding scope clearing efficiently as follows:

class MainViewModel : ViewModel() {
private fun makeNetworkRequest() {
viewModelScope.launch {
remoteApi.slowFetch()
// ...
}
}

// There is no need to override onCleared() method.
}

Navigation KTX

Fundamentally, each component of the Navigation library has its own KTX version, which adapts the API to be much more concise and Kotlin-idiomatic. In fact, Kotlin’s extension function and delegation property work to diminish the code. Besides, they can access destination arguments and navigate to destinations properly. For example:

class MyDestination : Fragment() {

val args by navArgs<MyDestinationArgs>()


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<Button>(R.id.next)
.setOnClickListener {
findNavController().navigate(R.id.action_to_next_destination)
}
}
//...

}

Or you can see the above example briefly as follows:

In conclusion

Essentially, Android KTX is a set of extensions to the Android framework aims at making your development with Kotlin much more clear, pleasant, and idiomatic for Android developers. This article introduced and discussed Android KTX by providing some examples. Using KTX could be helpful for writing more natural and concise Kotlin code in the future as a Kotlin developer based on Google resources.

Using Android Jetpack KTX (2024)

References

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 6349

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.