victor shagin
victor shagin

Reputation: 41

super.onbackpressed() in Jetpack Compose

I need to click on the image to go to the last activityenter image description here

error when calling the standard method

Upvotes: 2

Views: 2676

Answers (1)

z.g.y
z.g.y

Reputation: 6257

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()
        }
    )
}

Upvotes: 0

Related Questions