简体   繁体   English

在 XML/Compose 混合中导航出 Compose 活动

[英]Navigation out of a Compose activity in XML/Compose hybrid

I am working on a personal project and experimenting with Jetpack Compose.我正在从事个人项目并尝试使用 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.我目前在 XML 中拥有整个项目。我只是制作了一个导航到新片段和活动的按钮,但我使用 Compose 使该新活动成为可组合的。 My question is: How do I navigate out (back) of that Compose activity safely and properly?我的问题是:如何安全正确地导航出(返回)该 Compose 活动? 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.让我知道这是怎么回事和/或在 XML/Compose 混合体中处理后退导航的理想解决方案是什么。 This is the only Compose activity so using the Jetpack Navigator isn't the way I want to go.这是唯一的 Compose 活动,因此使用 Jetpack Navigator 不是我想要的方式 go。

Thanks in advance and great weekend!提前致谢,周末愉快!

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. Xml 或可组合项并不重要,因为活动仍然是活动,它将完成他的生命周期,并且活动托管的可组合项的生命周期也将干净利落地结束。

Only difference is how to get the activity instance, I would better suggest creating an extension function to get the activity more safely:唯一的区别是如何获取活动实例,我最好建议创建一个扩展 function 以更安全地获取活动:

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它将避免LocalContext.current as Activity的潜在崩溃,因为上下文并不总是一个activity ,也可以是一个ContextWrapper

and to end your activity on back press you could use Composable function BackHandler in your composable:并结束您的后退活动,您可以在可组合项中使用 Composable function BackHandler

BackHandler {
    activity?.finish()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM