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