Issue
I have a screen with a bottomsheet, but for the transition, and animation to work between activities I need the bottomsheet to be collapsed when the user goes on back pressed. I tried this
@Override
public void onBackPressed(){
if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
super.onBackPressed();
} else {
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
super.onBackPressed();
}
mShowingBack = false;
}
However, that doesn't work as the activity goes back while the bottomsheet is only halfway down.
Solution
BottomSheetBehavior.STATE_COLLAPSED doesn't hide all the BottomSheet, it just sets the height of the view to whatever you set with setPeekHeight() or behavior_peekHeight in the xml :) but putting that aside... you should call super.onBackPressed() inside a BottomSheetBehaviorCallback when the state of the BottomSheet is STATE_COLLAPSED, like this:
BottomSheetBehavior behavior = BottomSheetBehavior.from(mBottomSheetBehavior);
behavior.addBottomSheetCallback(new BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_COLLAPSED && mIsCollapsedFromBackPress){
mIsCollapsedFromBackPress = false;
super.onBackPressed();
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
// React to dragging events
}
});
and your backPressed() method should look like this:
@Override
public void onBackPressed(){
mIsCollapsedFromBackPress = true;
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
Answered By - amilcar-sr
Answer Checked By - Mildred Charles (JavaFixing Admin)