问题
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?
回答1:
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){ ...
回答2:
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);
}
});
回答3:
You could try overriding onOptionsItemSelected check for the id android.R.id.home and call finish() to go back to your previous activity.
回答4:
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;
}
来源:https://stackoverflow.com/questions/29781728/prevent-navigationdrawer-from-opening-on-home-button-click