You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多模块App使用Navigation跨模块跳转时销毁前序Activity异常

问题根因

你遇到的问题由两个错误共同导致:

  • Navigation API 用法错误
    ActivityNavigator 是 Navigation 组件内部绑定 NavController、管理返回栈的组件,不支持开发者手动 new 实例直接调用。你自行创建的 ActivityNavigator 实例完全脱离当前页面的导航管理体系,调用它的 popBackStack() 不会操作真实的页面返回栈,反而会打断新启动 Activity 的导航初始化流程。
    另外你要销毁跳转前的 Activity A,根本不需要调用 popBackStack(),这个方法的作用是操作导航返回栈弹出 Fragment 目的地,不是用来销毁 Activity 的。
  • :ft_b 模块导航图存在非法配置
    你在 :ft_b 导航图的 SecondFragment 下,给 toFirstFragment action 配置的目的地是 @+id/auth_nav_graph,这个 ID 是 :ft_a 模块的导航图 ID。两个模块完全独立无依赖,:ft_b 既访问不到 :ft_a 的导航图资源,编译时生成的资源 ID 也和 :ft_a 侧不匹配,属于无效目的地。NavHost 解析导航图时遇到不存在的目的地引用会初始化失败,自然加载不出对应的 Fragment,表现为页面空白。
    你之前去掉 popBackStack() 跳转正常,只是因为刚进入 Activity B 时只会加载 startDestination 指向的 FirstFragment,不会触发 SecondFragment 下的错误 action,导航图不会走到解析失败的分支而已,这个配置错误一直存在。

修复方案

按以下步骤修改即可:

  1. 修正 :ft_b 模块的导航图错误
    把 SecondFragment 下 toFirstFragment action 的目的地改成当前模块内的 FirstFragment,删掉跨模块的非法 ID 引用:
<fragment
    android:id="@+id/secondFragment"
    android:name="com.smb.ft_b.presentation.secondView.SecondFragment"
    android:label="@string/second_fragment_label"
    tools:layout="@layout/fragment_second">
    <action
        android:id="@+id/toFirstFragment"
        app:destination="@id/firstFragment" />
    <argument
        android:name="isbn"
        app:argType="string" />
</fragment>

注意:独立模块之间不要在导航图里直接引用其他模块的资源 ID,编译期资源 ID 是模块内独立生成的,运行时必然匹配失败。

  1. 替换错误的跳转逻辑
    删掉手动 new ActivityNavigator 的代码,跨模块 Activity 跳转直接用原生 Intent 即可,要销毁 Activity A 直接在跳转后调用 finish():
startActivity(Intent(this, HomeActivity::class.java))
finish()

如果要符合 Navigation 组件的使用规范,也可以在 :ft_a 的导航图里声明指向 HomeActivity 的 Activity 目的地,配置清栈规则,之后通过 NavController 跳转即可自动销毁 Activity A:
先在 :ft_a 的 auth_nav_graph 里添加 Activity 目的地配置:

<activity
    android:id="@+id/toHome"
    android:name="com.smb.ft_b.presentation.HomeActivity"
    app:popUpTo="@id/auth_nav_graph"
    app:popUpToInclusive="true" />

跳转时直接调用:

findNavController().navigate(R.id.toHome)

这种写法不需要手动调用 finish() 或 popBackStack(),Navigation 组件会自动清掉跳转到 HomeActivity 之前的所有栈内页面。


内容的提问来源于stack exchange,提问作者Sergio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 00:21:49