I have an activity that is setup to work with Android Jetpack's NavigationUI
. This works well and I can navigate correctly except that if I navigate down 2 times, when I navigate up once, the app bar will shows the burger even though there's still one fragment in the childFragmentManager
's backstack.
Example:
I navigate to the Alice In Animation RSS feed (this is an RSS reader), then to the Love death & robots article of the feed. Then go back to the articles list. But I'm not yet at the top of the application. There should not be a burger menu here.
Here's my activity class:
class MainActivity: AppCompatActivity() {
private val navigation: NavController by lazy {
Navigation.findNavController(this, R.id.main_activity_host_fragment)
}
private val drawerLayout by lazy {
findViewById<DrawerLayout>(R.id.activity_main_navigation_drawer)
}
private val drawerToggle by lazy {
ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
}
private val appBarConfiguration by lazy {
AppBarConfiguration(navigation.graph, drawerLayout)
}
private val backstackCount inline get() = main_activity_host_fragment?.childFragmentManager?.backStackEntryCount ?: 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawerLayout.addDrawerListener(drawerToggle)
setupActionBarWithNavController(navigation, appBarConfiguration)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if(item?.itemId == android.R.id.home && backstackCount == 0) {
val isOpened = drawerLayout.isDrawerOpen(activity_main_navigation_view)
if(isOpened) drawerLayout.closeDrawers()
else drawerLayout.openDrawer(activity_main_navigation_view)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onSupportNavigateUp(): Boolean {
val result = navigation.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
drawerToggle.syncState()
return result
}
}
Here is my navigation graph:
As ianhanniballake commented, NavigationUI
handles the home button automatically. ActionBarDrawerToggle
shouldn't be used with AppBarConfiguration
.