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.