Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AndroidX Navigation Architecture Component programmatically in Kotlin without using xml?

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).

like image 240
Louis CAD Avatar asked Mar 30 '19 20:03

Louis CAD


Video Answer


2 Answers

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")
        }
    }
}
like image 163
Louis CAD Avatar answered Oct 15 '22 09:10

Louis CAD


In addition to the Louis example, take a look at the official nav-component guide - Build a graph programmatically using the Kotlin DSL.

like image 22
Valeriy Katkov Avatar answered Oct 15 '22 10:10

Valeriy Katkov