Let's now explore the Fragment KTX module, which contains utility functions for working with fragments. First, we'll define our new dependency constant:
object Android {
...
object Ktx {
const val core = "androidx.core:core-ktx:1.0.1"
const val fragment = "androidx.fragment:fragment-ktx:1.0.0"
}
}
Now, we'll update app/build.gradle.kts:
dependencies {
...
implementation(Deps.Android.Ktx.core)
implementation(Deps.Android.Ktx.fragment)
}
Once the dependency is added, we can define FragmentTransactions using the commit() extension function like this:
supportFragmentManager.commit {
addToBackStack("fragment name")
add(SampleFragment(), "tag")
setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out)
}
This makes the addition of new FragmentTransaction feel more Kotlin idiomatic and removes some of the boilerplate around those operations.
As we've seen with Core KTX and Fragment KTX, these libraries can really improve the Android development experience. These types of extensions and additions are available across the Android KTX dependencies and can really help you take advantage of Kotlin for Android development.
In the next section, we'll take a look at the Kotlin Android Extensions plugin and how that provides additional functionality that makes Android development easier with Kotlin.