如何使用导航组件库从底部导航更改片段更改上的工具栏图标?

时间:2020-09-16 05:51:49

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

我已经使用navHostController设置了底部导航,我有一个带有工具栏的容器活动,我想根据我所在的片段来更改工具栏中的图标,如果我不使用它,这很容易导航组件库。

MainActivity

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    bottomNavigationView.setupWithNavController(dashboardNavHostFragment.findNavController())
}

enter image description here

我想将工具栏中的图标更改为底部导航中的活动片段。

1 个答案:

答案 0 :(得分:2)

您可以使用addOnDestinationChangedListener
像这样:

navController.addOnDestinationChangedListener { _, destination, _ ->
   if(destination.id == R.id.xxxx) {
       toolbar.setNavigationIcon(R.drawable.xxxx)
   } else {
       //
   }
}