Reputation: 4314
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?
Upvotes: 52
Views: 64372
Reputation: 39
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)
}
Upvotes: 0
Reputation: 60913
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")
}
}
Upvotes: 4
Reputation: 1642
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")
}
}
Upvotes: 109
Reputation: 111
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)
}
Upvotes: 11