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?
How to navigate from a Composable to an Activity in Jetpack Compose?
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")
}
}
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)
}
Instead of using LocalContext.current
to navigate to another Activity from a Composable
you can pass the onClick
callback to Activity
/Fragment
and navigate like before. Here is an 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")
}
}
startNewActivity is a function pass context , any class and Bundle it can be null ,
.clickable { startNewActivity(context,DetailsActivity::class.java) },
fun startNewActivity(context: Context,activityClass: Class<*>, bundle: Bundle? = null){
val intent = Intent(context, activityClass)
bundle.let { intent.putExtras(bundle!!) }
context.startActivity(intent)
}
© 2022 - 2025 — McMap. All rights reserved.
ContextAmbient
to get aContext
. You might be able to use Navigation for Compose to create a nav graph that uses bothactivity()
andcomposable()
destinations, though I have not tried that yet. – CartogramContextAmbient
provides aContext
. Though it appears to be being renamed toAmbientContext
, based on the source code. – CartogramstartActivity()
function you are trying to call. The error is showing that you are passing anIntent
to it, and it is expecting aContext
(at least as the first parameter). YourIntent
is coming from theIntent()
constructor that you are calling. I was expecting you to doval context = ContextAmbient.current; context.startActivity(Intent(context, ListActivity::class.java))
(semicolon used here just because Stack Overflow comments can't handle newlines). – Cartogram