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

使用Navigation组件加载Fragment后如何销毁该Fragment(启动页场景)

解决方案

要实现启动页Fragment跳转后销毁、按返回键不再出现,核心是利用Navigation组件的回退栈管理能力,跳转时将SplashFragment从回退栈中移除即可,提供两种常用实现方案:


方案1:代码跳转时动态配置规则

修改SplashFragment中跳转首页的逻辑,给navigate方法传入NavOptions配置项:

Handler(Looper.getMainLooper()).postDelayed({
    val navOptions = NavOptions.Builder()
        // 指定回退到splashFragment的位置
        .setPopUpTo(R.id.splashFragment, 
        // inclusive设为true表示连splashFragment一起弹出回退栈
        true)
        .build()
    findNavController().navigate(R.id.action_splashFragment_to_homeFragment, null, navOptions)
},6000)

方案2:导航图XML预配置(更推荐)

直接在导航图配置文件中给跳转Action加属性,后续所有调用这个Action的地方都会自动清理启动页,无需修改业务代码:

<fragment
    android:id="@+id/splashFragment"
    android:name="你的包名路径.SplashFragment">
    <action
        android:id="@+id/action_splashFragment_to_homeFragment"
        app:destination="@id/homeFragment"
        <!-- 新增以下两个属性 -->
        app:popUpTo="@id/splashFragment"
        app:popUpToInclusive="true" />
</fragment>

两种方案任选其一即可,配置完成后跳转到首页时,SplashFragment会被自动销毁并移出回退栈,按下返回键不会再回到启动页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:30:03