Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigation Component, Control when to show hamburger or back icon

I have the following Activity

class MainActivity : AppCompatActivity() {  private lateinit var drawerLayout: androidx.drawerlayout.widget.DrawerLayout  override fun onCreate(savedInstanceState: Bundle?) {     super.onCreate(savedInstanceState)     setContentView(R.layout.main_activity)      drawerLayout = drawer_layout      val navController = Navigation.findNavController(this, R.id.fragment_main_navHost)      setSupportActionBar(toolbar)      NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)     navView_main.setupWithNavController(navController) }  override fun onSupportNavigateUp(): Boolean {     return NavigationUI.navigateUp(drawerLayout,         Navigation.findNavController(this, R.id.fragment_main_navHost)) }  override fun onBackPressed() {     if (drawerLayout.isDrawerOpen(GravityCompat.START)) {         drawerLayout.closeDrawer(GravityCompat.START)     } else {         super.onBackPressed()     } } 

which as you can see is associated with navigation graph, and I am using a navigation drawer. When I am navigating through the items in the drawer I want to keep the hamburger icon, and only change it to up/back button when I click on an item within the fragment or popup for example and ensure that the behavior of the system reflects what the user expects based on the icon displayed. Is that possible

like image 394
Mustafa ALMulla Avatar asked Sep 04 '18 18:09

Mustafa ALMulla


1 Answers

To control when the AppBar navigation up/back show the following need to be done

1- create AppBarConfiguration and pass to it the top level destination and drawerLayout

    appBarConfiguration = AppBarConfiguration(         setOf(             R.id.dest_one,             R.id.dest_two         ),         drawerLayout     ) 

2- Tell the AppBar about the configration and navigation. this will help to show a title and show up arrow or drawer menu icon

setupActionBarWithNavController(navController, appBarConfig) 

3- Finally override the onOptionsItemSelected and onSupportNavigateUp and the Navigation Component extension to inform the AppBar how to behave

    override fun onOptionsItemSelected(item: MenuItem)= item.onNavDestinationSelected(findNavController(R.id.my_nav_host_fragment))         || super.onOptionsItemSelected(item)   override fun onSupportNavigateUp() = findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration) 

Reference Google Code Lab Navigation Navigation Codelab

like image 157
Mustafa ALMulla Avatar answered Oct 07 '22 12:10

Mustafa ALMulla