如何防止使用setupWithNavController的BottomNavigationView快速点击崩溃
这是对「如何防止视图双击」问题的延伸,针对底部导航场景,尤其是通过setupWithNavController()配置的BottomNavigationView。
传统的自定义点击监听器、对比上次点击时间的方案在此场景下失效,因为点击事件现在由Android NavigationUI统一处理。
例如我在Fragment中按如下方式配置BottomNavigationView:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val navHostFragment = childFragmentManager.findFragmentById(R.id.content_nav_host) as NavHostFragment val navController = navHostFragment.findNavController() val bottomNavigationView = view.findViewById<BottomNavigationView>(R.id.bottom_navigation) bottomNavigationView.setupWithNavController(navController) }
如果过快切换底部导航对应的Fragment,会触发如下报错:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.project, PID: 11136 java.lang.IllegalArgumentException: No destination with ID 2131296272 is on the NavController's back stack. The current destination is Destination(com.example.project/page1) label=page1 class=com.example.project.features.main.page1.Page1Fragment at androidx.navigation.NavController.getBackStackEntry(NavController.java:1358)

异常触发原因是Fragment仍在执行onViewCreated()生命周期时,导航操作已触发并修改了NavController的回退栈,此时首次访问Fragment的ViewModel就会触发报错。
最简便的解决思路是从源头限制BottomNavigationView的快速点击行为。
演示代码与栈追踪
内容的提问来源于stack exchange,提问作者BabyishTank
相关产品推荐
相关产品推荐

