Can not open navigation drawer on action bar item

2019-08-15 18:03发布

问题:

i want the right drawer to be opened on menu click i have used the following code but its not working for some reason

mDrawerToggle = new ActionBarDrawerToggle(getActivity(),mDrawerLayout,toolbar, R.string.drawer_open,
            R.string.drawer_close) {

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item != null && item.getItemId() == R.id.more) {
                if (mDrawerLayout.isDrawerOpen(Gravity.END)) {
                    saveToPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,mUserLearnedDrawer+"");
                    mDrawerLayout.closeDrawer(Gravity.END);
                } else {
                    mDrawerLayout.openDrawer(Gravity.END);
                }
            }
            return false;
        }
    };

please help me out

SOLVED IT BY MODIFYING THE MAINACTIVITY

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        case R.id.more:
            if (notificationDrawerFragment.mDrawerLayout.isDrawerOpen(Gravity.END)){
                notificationDrawerFragment.mDrawerLayout.closeDrawer(Gravity.END);
            }
            else
            { notificationDrawerFragment.mDrawerLayout.openDrawer(Gravity.END);
            }

        default:
            return super.onOptionsItemSelected(item);
    }
}

回答1:

Solved the following by modifying the menu option within the main activity

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        case R.id.more:
            notificationDrawerFragment.mDrawerLayout.openDrawer(Gravity.END);

        default:
            return super.onOptionsItemSelected(item);
    }
}


回答2:

Do you have this override:

@Override
protected void onPostCreate(Bundle savedInstanceState) {
      super.onPostCreate(savedInstanceState);
      mDrawerToggle.syncState();
}

also you should have overrides under ActionBarDrawerToggle:

public void onDrawerOpened(View drawerView) and
public void onDrawerClosed(View drawerView)


回答3:

Try this, I had learnt this from SO:

@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item != null && item.getItemId() == android.R.id.more) {
                if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
saveToPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,mUserLearnedDrawer+" ");
                    mDrawerLayout.closeDrawer(Gravity.RIGHT);
                } else {
                    mDrawerLayout.openDrawer(Gravity.RIGHT);
                }
            }
            return false;
        }
    };

Hope this helps.