Home:ALL Converter>Android Navigation Architecture Component - Programmatically

Android Navigation Architecture Component - Programmatically

Ask Time:2018-09-11T23:26:37         Author:Keith Kowalski

Json Formatter

Looking for examples or anything similar that takes Swift (iOS) code like this:

let navController = UINavigationController(rootViewController: initialView)

and sets it up in Kotlin, via the new Navigation component. I've referenced the following examples, but it's not making complete sense to me:

val myNavHostController: NavHostFragment = nav_host_fragment as NavHostFragment
val inflater = myNavHostController.navController.navInflator
val graph = inflater.inflate(R.layout.nav_graph)
myNavHostController.navController.graph = graph

and

val finalHost = NavHostFragment.create(R.navigation.example_graph)
supportFragmentManager.beginTransaction()
    .replace(R.id.nav_host, finalHost)
    .setPrimaryNavigationFragment(finalHost) // this is the equivalent to app:defaultNavHost="true"
    .commit()

It appears the Android examples I'm coming across, still require an Activity/Fragment to already be established in the XML file created by the navigation component ... but, what if I want this functionality to be dynamic? What if I need to set the 'host' activity for the nav component based on data passed in? I am in need of the ability to do this all via code, which is what the Swift line is doing (setting the 'initialView' UIViewController, as the 'host', which has the navigation controller embedded in it). None of it is done via storyboarding, which seems to be what Android wants me to do regardless...

I am certain the issue is me not fully understanding how this works in Android, which is what I really would like to learn.

Author:Keith Kowalski,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52279388/android-navigation-architecture-component-programmatically
yy