implementation 'com.android.support:support-core-utils:x.y.z'
DrawerLayout drawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.navigation_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawerLayout.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this);
@Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } }This code handles the behavior when the back button is pressed. If the navigation drawer is open, it closes it. Otherwise, it performs the default action of going back to the previous screen. The package library for DrawerLayout is android.support.v4.widget.