2

I successfully implemented a Navigation Drawer in my app, linking each item of the menu to a fragment. The destination fragment hides the DrawerToggle and displays the up button (i.e. the arrow icon), but for whatever reason, if I click on it, it opens the drawer and I can't go back to the previous fragment. I have to press the back button to do it. How can I change this behaviour? Is it possible to solve this without adding code in every fragment?

What I use:

  • Navigation Component
  • One activity, some fragments
  • Toolbar
  • AppBarConfiguration

MainActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Setup FTUE conditional navigation
        setupNavigation()

        setupNavigationDrawer()

        appBarConfiguration =
            AppBarConfiguration(
                setOf(R.id.overviewFragment, R.id.registrationFragment,
                       R.id.registrationParamFragment), drawerLayout)
        setupActionBarWithNavController(navController, appBarConfiguration)
        findViewById<NavigationView>(R.id.nav_view)
            .setupWithNavController(navController)
    }

    /**
     * Set the toolbar, set the drawerLayout, set the drawerToggle
     */
    private fun setupNavigationDrawer() {
        toolbar = findViewById(R.id.toolbar)

        setSupportActionBar(toolbar)

        drawerLayout = (findViewById<DrawerLayout>(R.id.drawer_layout))
            .apply {
                setStatusBarBackground(R.color.colorPrimaryDark)
            }
        drawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
        drawerToggle.setDrawerIndicatorEnabled(true)
        drawerToggle.syncState()

        drawerLayout.addDrawerListener(drawerToggle)

    }

    override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onPostCreate(savedInstanceState, persistentState)
        drawerToggle.syncState()
    }

    /**
     * Ensures that the drawer is closed
     * before the app switches back to the previous fragment
     */
    override fun onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }
}

Full repository: Github

MrWhoever
  • 31
  • 4

2 Answers2

3

You need to set your toolbar up with the nav controller:

toolbar.setupWithNavController(findNavController(R.id.nav_host_fragment),findViewById(R.id.full_drawer_layout))

There is more information on this here.

Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61
0

Why not make use of inheritance? Create MonitorCardiacoActivity That has this code and every Activity you use should inherit MonitorCardiacoActivity.

Uriel Frankel
  • 14,304
  • 8
  • 47
  • 69