I'm developing an app in Kotlin using some of the latest Android Jetepack components. I've recently had a bit of a hitch with the following case:
This issue seems to occur when using BottomNavigationView
with NavController
, and when each Fragment
has its own Toolbar
. The problem is that when transitioning from Fragment A to Fragment B, changes to titles and ActionBar navigation icons are updated in Fragment A and B. Ideally, for a smooth transition there would be no change to the state of the AppBar in Fragment A. I have a suspicion this might stem from the fact that these properties don't "belong to" the Toolbar
as this doesn't seem to affect the Toolbar's menu items in the same way.
A work-around for the AppBar titles is setting the title property of each Toolbar in its respective fragment_layout.xml, while also removing the label property from the navFragment.xml (which is usually responsible for setting the title text of the AppBar when using the navController).
However, this doesn't solve the issue of actionBar navigation icons like the Up / Home button which don't appear on top-level destinations but do on others. And so in my case it still appears pretty janky.
I've wired up the nav as follows:
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var appBarConfiguration: AppBarConfiguration
lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: MainActivityBinding = DataBindingUtil.setContentView(this, R.layout.main_activity)
navController = Navigation.findNavController(this, R.id.nav_fragment)
appBarConfiguration = AppBarConfiguration(setOf(R.id.fragment_1_main, R.id.fragment_2_main))
binding.bottomNavigationView.setupWithNavController(navController)
}
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
ExampleFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).setSupportActionBar(toolbar)
NavigationUI.setupWithNavController(toolbar, (requireActivity() as MainActivity).navController, (requireActivity() as MainActivity).appBarConfiguration)
}
Halp!