利用bottomNavigationView + navigation component能快速实现底部导航,只需要把navigation文件里的id和bottomNavigationView设置的menu里的id一致就可以实现,不用自己用supportFragmentManager切换fragment,还要重写bottomNavigationView的选择事件。说实话之前的方法挺麻烦。
但是利用利用bottomNavigationView + fragment component这个实现出现了问题,每次点击切换导航,fragment都会重新创建这样体验会很不好。
但是有什么办法解决呢?
官方给的navigation component里的demo里,有一个NavigationExtensions.kt扩展。把其拷贝到自己项目,参照官方的例子写即可。
private fun setupBottomNavigationBar() { val navGraphIds = listOf(R.navigation.home, R.navigation.analysis, R.navigation.matrix, R.navigation.user) // Setup the bottom navigation view with a list of navigation graphs val controller = nav_view.setupWithNavController( navGraphIds = navGraphIds, fragmentManager = supportFragmentManager, containerId = R.id.nav_host_fragment, intent = intent ) // Whenever the selected controller changes, setup the action bar. controller.observe(this, Observer { navController -> navController.addOnDestinationChangedListener { controller, destination, arguments -> nav_view.visibility = if (destination.id in fragmentIds) View.VISIBLE else View.GONE } }) }
controller.observe(this, Observer { navController -> navController.addOnDestinationChangedListener { controller, destination, arguments -> nav_view.visibility = if (destination.id in fragmentIds) View.VISIBLE else View.GONE } })
该部分代码是为了解决在其他fragment页面里bottomNavigationView还显示的问题。
本来我是把所有的fragment写在一个navigation文件中,现在分开写成4个。
一定要主意就是每个navigation文件中的navigation标签的id一定要和你bottomNavigationView里的menu的id一致,否则点击底部导航会没反应。