Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate from a composable to an activity or a fragment 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 StartActivity(..) method or the only way is to create Screens and NavController?

enter image description here

like image 929
Sweta Jain Avatar asked Dec 01 '20 09:12

Sweta Jain


People also ask

How do you start a composable activity?

Create a new activity by right-clicking on the project folder, click on new, click on Activity, and select the Gallery option. In the Gallery option, select Empty Compose Activity and name it SecondActivity as shown in the below images.

What is composable in jetpack compose?

Jetpack Compose is built around composable functions. These functions let you define your app's UI programmatically by describing how it should look and providing data dependencies, rather than focusing on the process of the UI's construction (initializing an element, attaching it to a parent, etc.).

Should I pass ViewModel to composable?

We recommend screen-level composables use ViewModel instances for providing access to business logic and being the source of truth for their UI state. You should not pass ViewModel instances down to other composables.


2 Answers

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")
    }
}
like image 72
Aystub Avatar answered Sep 28 '22 16:09

Aystub


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)
}
like image 29
Andrew Kornovan Avatar answered Sep 28 '22 16:09

Andrew Kornovan