user2872856
user2872856

Reputation: 2051

Close Navigation Drawer on back pressed

I have a material designed navigation drawer created following this tutorial.

When back button is pressed, the app quit. What I want to do is to close the navigation drawer on back pressed. This is the original code:

drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);

I added this:

public void onBackPressed() {
        if (this.drawerFragment.isDrawerOpen(GravityCompat.START)) {
            this.drawerFragment.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

However, I got error cannot resolve method isDrawerOpen and closeDrawer.

How can I get it to work?

Upvotes: 6

Views: 7504

Answers (1)

Yaw Asare
Yaw Asare

Reputation: 548

I think you shouldn't be using the fragment to open and close the drawer. instead try using the drawer layout.

public void onBackPressed() {
    DrawerLayout layout = (DrawerLayout)findViewById(R.id.drawer_layout);
    if (layout.isDrawerOpen(GravityCompat.START)) {
        layout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

Upvotes: 21

Related Questions