How to close Drawer after changing orientation?

Asked

Viewed 32 times

0

How do I get my Drawer to close after a change of orientation? Example: At first I opened the Drawer, right after I turned my smartphone horizontally, now I want this Drawer that April previously closed!

1 answer

0

The following code closes/opens Drawer:

button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    } else {
        mDrawerLayout.openDrawer(Gravity.LEFT); 
    }  
})

You can use in the event that changes the orientation:

orientationListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) {
        public void onOrientationChanged(int orientation) {
            if(canShow(orientation)){
                show();
            } else if(canDismiss(orientation)){
                dismiss();
            }
        }
    };

@Override
public void onResume(){
    super.onResume();
    orientationListener.enable();
}

@Override
public void onPause(){
    super.onPause();
    orientationListener.disable();
}

private boolean isLandscape(int orientation){
        return orientation >= (90 - THRESHOLD) && orientation <= (90 + THRESHOLD);
    }

private boolean isPortrait(int orientation){
    return (orientation >= (360 - THRESHOLD) && orientation <= 360) || (orientation >= 0 && orientation <= THRESHOLD);
}

public boolean canShow(int orientation){
    return !visible && isLandscape(orientation);
}

public boolean canDismiss(int orientation){
    return visible && !dismissing && isPortrait(orientation);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.