3

I'm trying to launch an Activity by clicking on a button set on a BottomNavBar. There's a Compose Navigation set up using NavGraphBuilder.navigation() with a composable() call for each Compose screen like:

navigation(
    startDestination = "home",
    route = "main"
) {
    composable("home") {
       HomeScreen(...)
    }

    // Several more Screens

}

I've found out about NavGraphBuilder.activity(), so I was thinking something like:

    activity("tickets") {
        this.activityClass = ExternalActivity::class
    }

And it works, if ExternalActivity doens't need any data to be passed to it. But it does.

The only viable alternative that comes to mind is using a composable() and launching the activity from there:

    composable("tickets") { backStackEntry ->
        val config = // get config from arguments
        context.startActivity(
            Intent(context, ExternalActivity::class.java).apply {
                putExtra("config", config)
            }
        )
    }

Or something along those lines. But it's kind of messy and has some side effects, so I'd like to avoid it.

Is there any way to use the activity() call and pass data to the Activity being launched?

I'm limited by the architecture of the codebase in which I'm working, so yes, it needs to be an Activity (it's actually from an external library).

Thanks.

Mario MG
  • 364
  • 2
  • 13

1 Answers1

0

The only thing that remotely resembles what you are trying to do would be data.

activity("tickets") {
    this.activityClass = ExternalActivity::class
    this.data = "Hello World".toUri()    <--
}

[ExternalActivity]
override fun onCreate(savedInstanceState: Bundle?) {
    ...
    val data = intent.data

But data is Uri, so it might not suit your needs, especially if you are dealing with an external library. Then context.startActivity() would be the next choice, as in your second approach.

One thing to note is that when you use context.startActivity() (instead of NavGraphBuilder.activity()), you need to set the "current" destination correctly when the Activity closes (e.g. call navController.navigateUp() or navController.popBackStack()). If not, it will jump back to the Activity you just closed, because as far as NavController is concerned, the Activity you started (and now closed) is the current destination.

solamour
  • 2,764
  • 22
  • 22