tccpg288 tccpg288 - 1 year ago 131
Java Question

DrawerLayout Back Arrow Functionality

I have successfully determined that to change the icon in the NavDrawer between the hamburger and arrow, this code needs to be toggled:


However, when I click the back button it is still opening the navigation drawer when indeed I want to return to the previous activity.

I know I could simply set an onClickListener, but I figured Android had a more native way of navigating to the previous screen. Here is my code:'


mDrawerLayout = (DrawerLayout) findViewById(;
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {

* Called when a drawer has settled in a completely closed state.
public void onDrawerClosed(View view) {
isOpen = false;

* Called when a drawer has settled in a completely open state.
public void onDrawerOpened(View drawerView) {
isOpen = true;

mDrawerList = (ListView) findViewById(;
ArrayList<String> drawerTitleArray = new ArrayList<>();
drawerTitleArray.add(0, "TEST");
drawerTitleArray.add(1, "TEST 1");
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, drawerTitleArray));


public boolean onOptionsItemSelected(MenuItem item){
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);

protected void onPostCreate(Bundle savedInstanceState) {
// Sync the toggle state after onRestoreInstanceState has occurred.

Answer Source

Actually, the syncState() method ensures that the toggle's image is in a matching state with the drawer, and sets the image on the Toolbar/ActionBar. It doesn't toggle the drawer/back functionality.

The setDrawerIndicatorEnabled() method is what you're looking for. When the indicator is enabled, the toggle operates the drawer. When it is disabled, it falls back on the navigation OnClickListener, if you've set one.

To handle the back functionality, add the following to the toggle's setup:

mDrawerToggle.setToolbarNavigationClickListener(new OnClickListener() {
        public void onClick(View v) {

Then, when you want to disable the drawer operation, and allow clicking the toggle to go back, simply call:


I would also point out that, since you've used the ActionBarDrawerToggle constructor that takes a Toolbar argument, the Activity's onOptionsItemSelected() method will not be called when clicking the toggle, and the mDrawerToggle.onOptionsItemSelected(item) call isn't needed there.

NB: Depending on the support library version you're using, the back arrow Drawable resource might be named R.drawable.abc_ic_ab_back_material instead. Please refer to this post for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download