Issue
I need to click on the image to go to the last activity
error when calling the standard method
Solution
This is the most easiest way but not
a safe and should not
be a recommended one since we don't know what context could be here, but if it's just for testing activity switching, this might suffice.
val context = LocalContext.current
...
...
.clickable {
(context as <Your Activity>).finish() // cast context to what ever the name of your Activity is
}
So consider the 2 approaches below.
Either you create a deep nest of passing your activity instance like this (assuming your Image
is within this composable scope)
@Composable
fun MyComposable(activity: Activity) { // activity parameter
...
...
Image(
modifier = Modifier.clickable {
activity.finish() // use it here
}
)
}
or you can utilize CompositionLocalProvider
, setting your activity instance within the scope of the contained composable
val LocalActivity = staticCompositionLocalOf<ComponentActivity> {
error("LocalActivity is not present")
}
class MyActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CompositionLocalProvider(LocalActivity provides this@MyActivity) {
MyAppTheme {
MyComposable()
}
}
}
}
}
then using it like this,
@Composable
fun MyComposable() {
...
...
val myActivityInstance = LocalActivity.current
Image(
modifier = Modifier.clickable {
myActivityInstance.finish()
}
)
}
Answered By - z.g.y
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.