【问题标题】:System back button not working in Navigation Component系统后退按钮在导航组件中不起作用
【发布时间】:2022-01-09 07:11:33
【问题描述】:

我必须在 Fragment(MainFragment) 和导航组件内的所有其他 Fragment 中实现 Navigation Component

我只是想处理在 MainFragment 中实现的 Navigation 上的系统后按

我最初将我的 MainFragment 添加到 MainActivity 之类的

if (savedInstanceState == null) {
            val bundle = bundleOf("sourceType" to 0)
            supportFragmentManager.commit {
                setReorderingAllowed(true)
                add<MainFragment>(R.id.fragment_container_view, args = bundle)
            }
        }

现在在 MainFragment 我添加了 NavHost(Navigation Component) 。我有两个片段CategoryFragment(开始目的地)GalleryFragment。现在,当我使用方向从 CategoryFragment 移动到 GalleryFragment 时。

按下后它应该移动到 CategoryFragment 但它会杀死我的应用程序

为什么会这样?

据我所知,它应该移到上一个片段

MainFragment.kt

class MainFragment : Fragment(R.layout.fragment_main){
    private val mViewModel by viewModels<MainViewModel>()
    private val mBinding: FragmentMainBinding by viewBinding()
    
    lateinit var mainSearchNavHostFragment: NavHostFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        /*val onBackPressCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if(mainSearchNavHostFragment.navController.currentDestination?.id == R.id.galleryFragment){
                    findNavController().popBackStack()
                }else findNavController().navigateUp()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this,onBackPressCallback)*/
    }

    private fun searchGallery(categoryToSearch:String){
        if(::mainSearchNavHostFragment.isInitialized){
            mainSearchNavHostFragment.navController.navigate(R.id.galleryFragment, Bundle().apply {
                putString("categoryType",categoryToSearch)
            })
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mainSearchNavHostFragment = childFragmentManager.findFragmentById(R.id.nav_host_fragment_content_main) as NavHostFragment
    }
}

或者我是否必须在每个片段中实现 OnBackPressedCallback,AFAIK 它应该默认完成。我做错了什么。

【问题讨论】:

    标签: android kotlin navigation fragment


    【解决方案1】:

    在使用导航组件和 ViewBinding 时,您不应该使用“supportFragmentManager.commit”或“childFragmentManager.findFragmentById”。

    【讨论】:

    • supportFragmentManager 写在 Activity 中,用于膨胀 MainFragment(实现 NavHost 的地方)。
    • @TaimoorKhan 这不是正确的方法。您可以在导航 xml 文件中设置 startDestination。
    • 我必须在开始时传递 bundle 参数。这不能通过 navigation.xml 完成
    • @TaimoorKhan 你可以在navigation.xml中定义参数并给它一个默认值。
    • 如果我想在运行时更改它怎么办。我的意思是我将它创建为任何应用程序的图库应用程序。任何项目通过 SourceType(Pixabay 或 Unsplash)然后它就会工作
    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多