【问题标题】:Navigation Component - BottomNavigationView - Don't keep startDestination fragment when back导航组件 - BottomNavigationView - 返回时不要保留 startDestination 片段
【发布时间】:2020-12-18 22:47:07
【问题描述】:

我正在使用导航组件和 BottomNavigationView 设置 UI。

3 个标签:主页、新闻、帐户。

当我从 Home 导航到 News(当前,Back stack 有 HomeFragment)并按下 Back 按钮时, Fragment News 将被销毁,Back stack 中的 HomeFragment 也将被销毁并创建新的 HomeFragment。我希望 Back stack 中的 HomeFragment 再次显示,不会破坏并创建新的。

我使用这个代码:

bottomNavigation.setupWithNavController(navHostFragment.findNavController())

如何解决这个问题?

谢谢。


更新问题:

当我点击菜单项时,片段将被创建新实例。我不希望这样,如果尚未单击它,我想导航到新的 Fragment,如果我再次单击菜单项,Fragment 将再次显示(不创建新的)。

【问题讨论】:

  • 我还没有找到解决方案,请帮助我。
  • 解决方案是使用FragmentManager,在onCreate()中添加所有Fragments,并根据需要显示/隐藏Fragments。检查上面我提到的答案。
  • 感谢支持,但我想将导航组件与 BottomNaviagtionView 一起使用。
  • 这就是我分享这个答案的原因。它不使用ViewPager

标签: android material-design bottomnavigationview android-architecture-navigation


【解决方案1】:

关于您更新的问题。如果您不想在重新选择时重新创建片段,只需在 BottomNavigationView 上设置 OnNavigationItemReselectedListener

    bottomNavigation.setOnNavigationItemReselectedListener { item ->
        when (item.itemId) {
            R.id.frag1-> {
                // do something on reselection or leave empty
            }
            R.id.frag2-> {
                // do something on reselection or leave empty
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2022-07-14
    • 2020-02-27
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多