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
相关产品推荐
相关产品推荐

