Android BottomSheetBehavior,如何禁用snap?

时间:2016-06-10 21:12:38

标签: android android-support-library bottom-sheet

标准android BottomSheetBehavior具有树状态:隐藏,折叠和展开。

我想允许用户在折叠和展开之间“离开”底页。现在,使用默认行为,它将捕捉到最近的折叠或展开。我该如何禁用此快照功能?

1 个答案:

答案 0 :(得分:3)

我将提出一种方法来实现View扩展BottomSheetDialogFragment的此类功能。

<强>展开:

首先过度使用onResume

@Override
public void onResume() {
    super.onResume();
    addGlobaLayoutListener(getView());
}

private void addGlobaLayoutListener(final View view) {
    view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            setPeekHeight(v.getMeasuredHeight());
            v.removeOnLayoutChangeListener(this);
        }
    });
}

public void setPeekHeight(int peekHeight) {
    BottomSheetBehavior behavior = getBottomSheetBehaviour();
    if (behavior == null) {
        return;
    }
    behavior.setPeekHeight(peekHeight);
}

上面的代码应该只是将BottomSheet peekHeight设置为视图的高度。这里的关键是函数getBottomSheetBehaviour()。实施如下:

private BottomSheetBehavior getBottomSheetBehaviour() {
    CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) ((View) getView().getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
    if (behavior != null && behavior instanceof BottomSheetBehavior) {
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
        return (BottomSheetBehavior) behavior;
    }
    return null;
}

这只是检查View的父级是否设置了“CoordinatorLayout.LayoutParams”。如果是,请设置适当的BottomSheetBehavior.BottomSheetCallback(下一部分需要),更重要的是返回CoordinatorLayout.Behavior,这应该是BottomSheetBehavior

<强>折叠:

这里有一个[`BottomSheetBehavior.BottomSheetCallback.onSlide(查看bottomSheet,float slideOffset)``](https://developer.android.com/reference/android/support/design/widget/BottomSheetBehavior.BottomSheetCallback.html#onSlide(android.view.View,float))正是我们所需要的。从[文档](https://developer.android.com/reference/android/support/design/widget/BottomSheetBehavior.BottomSheetCallback.html#onSlide(android.view.View,浮动)):

  

当底部纸张向上移动时,偏移量增加。从0到1,工作表处于折叠状态和展开状态之间,从-1到0处于隐藏状态和折叠状态之间。

这意味着崩溃检测只需要检查第二个参数:

在同一个类中定义BottomSheetBehavior.BottomSheetCallback

private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {

    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
            dismiss();
        }
    }

    @Override
    public void onSlide(@NonNull View bottomSheet, float slideOffset) {
        if (slideOffset < 0) {
            dismiss();
        }
    }
};