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

Kotlin使用Jetpack Navigation跳转后按返回键退出应用,如何返回上一个Fragment?

解决方案

问题根因

你的问题出在导航图nav_graph的跳转配置上,和VideoAdapter无关,给Adapter传入lifecycle仅用于管理Youtube播放器的生命周期,不会影响系统返回键逻辑。
你在action_homeFragment_to_youtubeFragment中配置了app:popUpTo="@id/homeFragment"和app:popUpToInclusive="true",这两行配置的作用是:跳转到YoutubeFragment时,将返回栈中直到HomeFragment的所有页面全部弹出,且包含HomeFragment本身。跳转完成后返回栈仅剩下YoutubeFragment,按下返回键没有上一级页面,自然会直接退出应用。

修复方案

方法1:修改导航图配置(推荐)

直接删除action_homeFragment_to_youtubeFragment下的两行多余配置即可,修改后的action代码如下:

<action
    android:id="@+id/action_homeFragment_to_youtubeFragment"
    app:destination="@id/youtubeFragment" />

修改完成后跳转时HomeFragment会保留在返回栈中,按下系统返回键就会自动回退到HomeFragment。

方法2:手动添加返回键监听(可选,适用于需要自定义返回逻辑的场景)

如果你有其他自定义返回逻辑的需求,可以在YoutubeFragment的onViewCreated方法中添加返回键回调,手动控制回退逻辑:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // 添加系统返回键监听
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
        findNavController().popBackStack()
    }
    // 原有逻辑保持不变
    val Dataset= viewModel.result.value
    binding.recyclerView.adapter= Dataset?.let {
        VideoAdapter(requireContext(),
            it,this.lifecycle)
    }
    binding.recyclerView.layoutManager = LinearLayoutManager(this.context)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:48:04