简体   繁体   中英

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?

在此处输入图像描述

In compose 1.0.0-alpha08 , use AmbientContext , in earlier versions of compose use LocalContext :

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

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

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

Beside using LocalContext.current to navigate to another Activity inside Composable .

If you able to pass the onClick callback to Activity/Fragment, you still able to navigate like before. Example

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AndroidTheme {
                Surface(...) {
                    Greeting (onClick = {
                        // this here is MainActivity

                        startDetailActivity()
                    })
                }
            }
        }
    }

    fun startDetailActivity() {
        val intent = Intent(this, DetailActivity::class.java)
        startActivity(intent)
    }
}

@Composable
fun Greeting(onClick: () -> Unit) {
    
    Button(onClick = onClick) {
        Text(text = "Button")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM