防止导航到同一片段 [英] Prevent navigating to the same fragment
问题描述
我正在使用带有BottomNavigationView 的Android 导航jetpack 库.我已经实现了 NavHost、NavGraph 和我的片段.当我使用操作进行导航时,一切都按预期工作.
I'm using Android navigation jetpack library with BottomNavigationView. I have implemented the NavHost, the NavGraph and my fragments. Everything is working as intented when I use actions to navigate.
我使用以下代码来设置一切:
I use the following code to setup everything:
val navController = Navigation.findNavController(this, R.id.nav_host)
bottom_navigation.setupWithNavController(navController)
问题是,如果我单击选项卡 2 次,片段将重新创建两次.有没有办法拦截导航?我不想导航到正在显示的同一个片段.
The problem is that if I click a tab 2 times the fragment is recreated twice. Is there any way to intercept navigation? I don't want to navigate to the same fragment that's being shown.
推荐答案
根据 这个问题,
随意设置 OnNavigationItemReselectedListener,它优先于 NavigationUI 设置的 OnNavigationItemSelectedListener
.
Feel free to set a OnNavigationItemReselectedListener, which takes precedence over the
OnNavigationItemSelectedListener
set by NavigationUI.
val navController = Navigation.findNavController(this, R.id.nav_host)
bottom_navigation.setupWithNavController(navController)
bottom_navigation.setOnNavigationItemReselectedListener {
// Do nothing to ignore the reselection
}
这篇关于防止导航到同一片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!