使用导航组件重新加载片段

时间:2020-09-11 02:47:37

标签: android kotlin android-fragments android-architecture-navigation

我正在使用导航组件加载片段,如下所示: https://developer.android.com/guide/navigation/navigation-getting-started

navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_opt1,
                R.id.navigation_opt2,
                R.id.navigation_opt3,
                R.id.navigation_more
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

我的工具栏顶部还有一个微调框。选择微调器项目后,我想重新加载/刷新片段及其视图模型。我尝试了下面的代码进行重新加载,但无法正常工作。另外,我知道我们不应该在导航组件中使用fragmentManager

val ftr: FragmentTransaction = requireFragmentManager().beginTransaction()
        ftr.detach(this).attach(this).commit()

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

抱歉回复晚了。我在相同的场景中使用下面的代码。 那可能会有所帮助。在您的微调器 ItemClick 中调用此方法。 我们必须使用 popbackstack 以避免一次又一次地添加相同的片段。

  private fun refreshCurrentFragment(){
        val id = navController.currentDestination?.id
        navController.popBackStack(id!!,true)
        navController.navigate(id)
    }