Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open navigation drawer when options menu button is pressed

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?

like image 769
Frozen Crayon Avatar asked Dec 30 '13 15:12

Frozen Crayon


2 Answers

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);
}
like image 145
Keyfe Ang Avatar answered Sep 17 '22 17:09

Keyfe Ang


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.)

like image 41
Andrew Avatar answered Sep 19 '22 17:09

Andrew