4

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

我想允许用户在折叠和展开之间“离开”底部工作表。现在,使用默认行为,它将根据最接近的折叠或展开对齐。我应该如何禁用此快照功能?

4

1 回答 1

6

我将介绍一种实现此类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,浮动 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 , float)):

随着该底部片材向上移动,偏移量增加。从 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();
        }
    }
};
于 2016-10-19T18:00:43.780 回答