Question

How to navigate from a Composable to an Activity in Jetpack Compose?

What are the ways in which navigation is possible between a composable and an Activity and vice versa? Can I do it by using the startActivity(...) method or is the only way to create Screens and NavController?

Android Studio Screenshot

 46  56680  46
1 Jan 1970

Solution

 100

In newer version of compose use LocalContext.
In older versions (1.0.0-alpha08 and before) use AmbientContext:

@Composable
fun MainScreen() {
    val context = LocalContext.current

    Button(onClick = {
        context.startActivity(Intent(context, ListActivity::class.java))
    }) {
        Text(text = "Show List")
    }
}
2020-12-07

Solution

 10

Here's how I usually do it (and pass values to another activity):

val context = LocalContext.current
...
onClick = {
    val intent = Intent(context, ListActivity::class.java)
    intent.putExtra(YourExtraKey, YourExtraValue)
    context.startActivity(intent)
}
2021-09-18