Android Bottomsheetbehavior, How To Disable Snap?
Solution 1:
I will present a way to achievie such functionality for a View extending BottomSheetDialogFragment.
Expanding:
First of all overrive onResume:
@OverridepublicvoidonResume() {
super.onResume();
addGlobaLayoutListener(getView());
}
privatevoidaddGlobaLayoutListener(final View view) {
view.addOnLayoutChangeListener(newView.OnLayoutChangeListener() {
@OverridepublicvoidonLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
setPeekHeight(v.getMeasuredHeight());
v.removeOnLayoutChangeListener(this);
}
});
}
publicvoidsetPeekHeight(int peekHeight) {
BottomSheetBehaviorbehavior= getBottomSheetBehaviour();
if (behavior == null) {
return;
}
behavior.setPeekHeight(peekHeight);
}
What the code above is supposed to do is just setting the BottomSheetpeekHeight to the heigth of the view. The key here is the function getBottomSheetBehaviour(). The implementation is below:
private BottomSheetBehavior getBottomSheetBehaviour() {
CoordinatorLayout.LayoutParamslayoutParams= (CoordinatorLayout.LayoutParams) ((View) getView().getParent()).getLayoutParams();
CoordinatorLayout.Behaviorbehavior= layoutParams.getBehavior();
if (behavior != null && behavior instanceof BottomSheetBehavior) {
((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
return (BottomSheetBehavior) behavior;
}
returnnull;
}
This just check if the parent of View has 'CoordinatorLayout.LayoutParams' set. If yes, sets appropriate BottomSheetBehavior.BottomSheetCallback (which is needed in the next part), and more importantly returns the CoordinatorLayout.Behavior, which is supposed to be BottomSheetBehavior.
Collapsing:
Here a [`BottomSheetBehavior.BottomSheetCallback.onSlide (View bottomSheet, float slideOffset)``](https://developer.android.com/reference/android/support/design/widget/BottomSheetBehavior.BottomSheetCallback.html#onSlide(android.view.View, float)) is just exactly what is needed. From the [documentation](https://developer.android.com/reference/android/support/design/widget/BottomSheetBehavior.BottomSheetCallback.html#onSlide(android.view.View, float)):
Offset increases as this bottom sheet is moving upward. From 0 to 1 the sheet is between collapsed and expanded states and from -1 to 0 it is between hidden and collapsed states.
This means, that just checking the second parameter is needed for collapse detection:
define BottomSheetBehavior.BottomSheetCallback in the same class:
private BottomSheetBehavior.BottomSheetCallbackmBottomSheetBehaviorCallback=newBottomSheetBehavior.BottomSheetCallback() {
@OverridepublicvoidonStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
}
}
@OverridepublicvoidonSlide(@NonNull View bottomSheet, float slideOffset) {
if (slideOffset < 0) {
dismiss();
}
}
};
Post a Comment for "Android Bottomsheetbehavior, How To Disable Snap?"