Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
user2872856 Avatar asked Jan 02 '16 02:01

user2872856


People also ask

What is back navigation in Android?

Back navigation is how users move backward through the history of screens they previously visited. All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI.

How to use navigation drawer in Android app?

The user can view the navigation drawer when the user swipes a finger from the left edge of the activity. They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is displayed on all top-level destinations that use a DrawerLayout.

How to use navigation drawer ACTIVITY in Android studio?

The drawer icon is displayed on all top-level destinations that use a DrawerLayout . To add a navigation drawer, first declare a DrawerLayout as the root view. Inside the DrawerLayout , add a layout for the main UI content and another view that contains the contents of the navigation drawer.


1 Answers

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();
    }
}
like image 141
Yaw Asare Avatar answered Nov 07 '22 09:11

Yaw Asare