您可以通过子类化
BottomSheetBehavior
并重写
onTouchEvent
方法,在
ACTION_UP
和
ACTION_CANCEL
时提前返回来实现此操作。
public class CustomBottomSheetBehavior<V extends View> extends BottomSheetBehavior<V> {
public CustomBottomSheetBehavior() {
super();
}
public CustomBottomSheetBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) {
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
return true;
}
return super.onTouchEvent(parent, child, event);
}
}
这将防止BottomSheetBehavior
类处理这些事件并触发“展开”或“折叠”调用。
在xml中应用您的CustomBottomSheetBehavior
:
app:layout_behavior="com.yourpackage.CustomBottomSheetBehavior"
当底部表单完全展开或折叠时,要恢复BottomSheetBehavior
的默认功能,可以添加一个标志,该标志在滑动偏移达到某个值时设置。在以下示例中,只有当滑动偏移在0.1和0.9之间时,才会忽略底部表单的ACTION_UP
和ACTION_CANCEL
事件。
public class CustomBottomSheetBehavior<V extends View> extends BottomSheetBehavior<V> {
private boolean isExpandedOrCollapsed;
public CustomBottomSheetBehavior() {
super();
listenForSlideEvents();
}
public CustomBottomSheetBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
listenForSlideEvents();
}
void listenForSlideEvents() {
setBottomSheetCallback(new BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
isExpandedOrCollapsed = slideOffset < 0.1f || slideOffset > 0.9f;
}
});
}
@Override
public boolean onTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) {
if (!isExpandedOrCollapsed) {
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
return true;
}
}
return super.onTouchEvent(parent, child, event);
}
}