不能在动作栏项目点击打开抽屉式导航栏(Can not open navigation drawer

2019-10-22 10:52发布

我想在菜单中,单击要打开的右抽屉我用下面的代码,但它不工作由于某种原因

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;
        }
    };

请帮我

解决它通过修改在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);
    }
}

Answer 1:

由主活动中修改菜单选项解决以下

 @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);
    }
}


Answer 2:

你有这样的控制装置:

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

你也应该有下覆盖ActionBarDrawerToggle

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


Answer 3:

试试这个,我从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;
        }
    };

希望这可以帮助。



文章来源: Can not open navigation drawer on action bar item click