tyczj
tyczj

Reputation: 73753

Prevent NavigationDrawer from opening on Home Button Click

I have a NavigationDrawer for my main activity, in one instance I show a fragment and the "Hamburger menu" changes into an arrow.

I disabled the ability to open the drawer via swipe when that fragment is shown by using this

mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

and it works fine but now the problem is the user can still open the drawer by clicking the home button "Arrow". I want the arrow to act as the back button and not open the drawer so how can I stop the drawer from opening?

Upvotes: 1

Views: 1661

Answers (4)

SachinGutte
SachinGutte

Reputation: 7055

I guess you need to use setNavigationOnClickListener() on toolbar to override drawer behavior.

Like -

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
        // logic to decide if drawer open/close, or pop fragment etc
     }
});

This does prevents drawer from opening by clicking on icon. But it does open by swiping. But that you already taken care of. So this should work.

Note This works only after you set ActionBarDrawerToggle by calling

mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,  toolbar, R.string.openDrawer, R.string.closeDrawer){ ...

Upvotes: 6

Joaquin Iurchuk
Joaquin Iurchuk

Reputation: 5617

Put this on your Activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getId() == android.R.id.home){
        doSomething(); //can be a finish()
    }
}

Or, from this answer

mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        popStackIfNeeded();
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        mActionBar.setDisplayHomeAsUpEnabled(false);
        mDrawerToggle.setDrawerIndicatorEnabled(true);
    }
});

Upvotes: 1

savepopulation
savepopulation

Reputation: 11921

try to override on options item select.

   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
             case android.R.id.home :
                // do what you want
                return true;
          }
          return true;
       }

Upvotes: 0

Jayesh Elamgodil
Jayesh Elamgodil

Reputation: 1477

You could try overriding onOptionsItemSelected check for the id android.R.id.home and call finish() to go back to your previous activity.

Upvotes: 0

Related Questions