Open navigation drawer when options menu button is

2020-07-06 07:29发布

问题:

I'd like the navigation drawer opened when the options menu button is pressed. So in my Sherlock Fragment activity I added:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mDrawerLayout.isDrawerOpen(mDrawerLinear)) {
        mDrawerLayout.openDrawer(mDrawerLinear);
    }
    return true;
}

For some reason nothing happens when the options menu button is pressed.

Otherwise the drawer is working fine. It opens when the app icon on the action bar is pressed or when I pull it. So what's wrong?

回答1:

Maybe your referring to onKeyDown (int keyCode, KeyEvent event)

sample:

@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        // your action...

        if (!mDrawerLayout.isDrawerOpen(mDrawerLinear)) {
            mDrawerLayout.openDrawer(mDrawerLinear);
        }
        return true;
    }
    return super.onKeyDown(keyCode, e);
}


回答2:

The answer above is good, I just want to add some clarification (open/close version):

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_MENU) {

        View drawerView = findViewById(R.id.navigation_drawer); // child drawer view

        if (!mDrawerLayout.isDrawerOpen(drawerView)) {
            mDrawerLayout.openDrawer(drawerView);
        } else if (mDrawerLayout.isDrawerOpen(drawerView)) {
            mDrawerLayout.closeDrawer(drawerView);
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Where mDrawerLayout is the parent activity layout and drawerView the child view for the drawer inside the activity layout (list or smth.)