禁用 BottomSheet 拖动

Disable BottomSheet Drag

由于我的声望点很低,我无法发表评论。所以我要扩展这个问题:

Ray W 提供的解决方案有效,但现在它通过在父视图 (CoordinatorLayout) 上滑动和拖动来展开。

Image

在该图像中,如果我在 "Unwanted Drag Area" 上拖动,BottomSheet 会向上滑动。如何过滤掉或停止不需要的视图上的触摸事件?

将 onInterceptTouchEvent 函数 return 的值从 更改为:

@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) {
  return super.onInterceptTouchEvent(parent, child, event) && mAllowUserDragging;
}

还有一件事,如果您在 BottomSheetLayout 中有一个 ListView,则在 ListView 中滚动项目会将 bottomSheetBehavior 状态从 "STATE_EXPANDED" 更改为 "STATE_DRAGGING"。 示例代码片段:

@Override
    public void onBackPressed() {    
        if(isBottomViewOpen){ // set this bool in behavior callback
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }else {
            super.onBackPressed();
        }
    }

看看这个:

mBottomSheetBehavior1.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                    mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                Log.i("BottomSheetCallback", "slideOffset: " + slideOffset);
            }
        });

onBackPress 时关闭 BottomSheet :

@Override
    public void onBackPressed() {
        if(mBottomSheetBehavior1.getState() != 4) {
            mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
        else {
            super.onBackPressed();
        }
    }

简单的解决方案,它解决了我遇到的两个问题。

1- 阻止拖动事件。

2- 解决listView滚动问题

CoordinatorLayout.Behavior<View> behavior;

View profile_config_layout_bottom_sheet = findViewById(R.id.list_view_audience_profile_config_layout);

CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) profile_config_layout_bottom_sheet.getLayoutParams();
behavior = layoutParams.getBehavior();
assert behavior != null;
((BottomSheetBehavior<View>) behavior).addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_DRAGGING) {
            ((BottomSheetBehavior<View>) behavior).setState(BottomSheetBehavior.STATE_EXPANDED);
        } 
    }
    @Override
    public void onSlide(@NonNull View bottomSheet, float slideOffset) {}
});

显示对话框:

((BottomSheetBehavior) behavior).setState(BottomSheetBehavior.STATE_EXPANDED);

对于 Kotlin,只需在您的代码中添加以下行,

behaviour.isDraggable = false