gpt4 book ai didi

Android BottomSheetBehavior,如何禁用快照?

转载 作者:太空宇宙 更新时间:2023-11-03 13:15:05 26 4
gpt4 key购买 nike

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

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

最佳答案

我将展示一种方法来为扩展BottomSheetDialogFragmentView 实现此类功能。

扩展:

首先覆盖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 设置为 View 的高度。这里的关键是函数 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 (View 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 , 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.

这意味着,只需检查第二个参数即可进行崩溃检测:

在同一个类中定义 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();
}
}
};

关于Android BottomSheetBehavior,如何禁用快照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37757240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com