I have an screen with a bottomsheet, but for the transition animation to work between activites 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 doesnt work as the activity goes back while the bottomsheet is only half way down.
Disable drag of BottomSheetDialogFragment Even if we have made the BottomSheetDialogFragment as expanded, user can hold the top part of the BottomSheet and drag to show peek view. It can also be disabled by overriding onStateChanged() . This will set the expanded state even if user drags the view.
↳ com.google.android.material.bottomsheet.BottomSheetDialogFragment. Modal bottom sheet. This is a version of DialogFragment that shows a bottom sheet using BottomSheetDialog instead of a floating dialog.
In android, there are two types of bottom sheets that use most of the time, Persistent Bottom Sheet and Modal Bottom Sheet. Persistent Bottom Sheet: It shows in-app content. It will display at the bottom of the mobile screen making some amount of the content visible.
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);
}
behavior.setBottomSheetCallback();
Is now deprecated. Use this one instead.
BottomSheetBehavior.from(nearbyBottomSheet).addBottomSheetCallback(object :BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With