The docs of AndroidX Navigation currently mostly cover usage from xml. I'd like to see an example of programmatic usage with Kotlin, with Fragments (because I'm not aware of another navigator at the moment).
Here's a simple example of how one can use AndroidX Navigation programmatically using Fragments with the KTX artifacts:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val container = frameLayout(id = R.id.content) // From Splitties Views DSL. Equivalent to FrameLayout().apply { id = R.id.content }
setContentView(container)
// Add the NavHostFragment if needed
if (savedInstanceState == null) supportFragmentManager.transaction(now = true) {
val fragment = NavHostFragment()
add(R.id.content, fragment)
setPrimaryNavigationFragment(fragment)
}
// Use the Kotlin extension from the -ktx dependencies
// to find the NavController for the given view ID.
val navController = findNavController(R.id.content)
// Create the graph using the Kotlin DSL, setting it on the NavController
navController.graph = navController.createGraph(startDestination = R.id.nav_dest_main) {
fragment<MainFragment>(R.id.nav_dest_main) {
label = TODO("Put an actual CharSequence")
}
fragment<SomeFragment>(R.id.nav_dest_some_fragment) {
label = TODO("Put an actual CharSequence")
}
}
}
In addition to the Louis example, take a look at the official nav-component guide - Build a graph programmatically using the Kotlin DSL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With