Home > database >  Navigation out of a Compose activity in XML/Compose hybrid
Navigation out of a Compose activity in XML/Compose hybrid

Time:01-19

I am working on a personal project and experimenting with Jetpack Compose. I currently have the whole project in XML. I just made a button that navigates to a new Fragment and Activity, but I used Compose to make that new activity a Composable. My question is: How do I navigate out (back) of that Compose activity safely and properly? My current solution is to get the activity with:

val activity = LocalContext.current as Activity

and to call:

onClick = {
    activity.finish()
}

Let me know how this fares and/or what is the ideal solution to deal with back navigation in an XML/Compose hybrid. This is the only Compose activity so using the Jetpack Navigator isn't the way I want to go.

Thanks in advance and great weekend!

CodePudding user response:

This is indeed the correct way to end an activity from a composable.

Xml or composable doesnt matter since an activity is still an activity, it will finish his lifecycle and lifecycle of composables hosted by the activity will cleanly end too.

Only difference is how to get the activity instance, I would better suggest creating an extension function to get the activity more safely :

fun Context.getActivity(): AppCompatActivity? = when (this) {
is AppCompatActivity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
}

It will avoid potential crashes on your LocalContext.current as Activity since a context is not always an activity and can also be a ContextWrapper

and to end your activity on back press you could use Composable function BackHandler in your composable :

BackHandler {
    activity?.finish()
}
  • Related