標準android BottomSheetBehavior具有樹狀態:隱藏,摺疊和展開。Android BottomSheetBehavior,如何禁用捕捉?
我想允許用戶在摺疊和展開之間「離開」底部工作表。現在,使用默認行爲,它將捕捉到最接近的摺疊或展開。我應該如何禁用這個捕捉功能?
標準android BottomSheetBehavior具有樹狀態:隱藏,摺疊和展開。Android BottomSheetBehavior,如何禁用捕捉?
我想允許用戶在摺疊和展開之間「離開」底部工作表。現在,使用默認行爲,它將捕捉到最接近的摺疊或展開。我應該如何禁用這個捕捉功能?
我將介紹一種實現View
擴展BottomSheetDialogFragment
的此類功能的方法。
擴大:
首先overrive 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
設置視圖的heigth。這裏的關鍵是功能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,浮動))只是究竟需要什麼。從[文檔](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();
}
}
};