BottomSheetBehavior全展开状态RecyclerView向下滑动带动BottomSheetBehavior
时间: 2023-05-27 20:01:22 浏览: 259
BottomSheetBehavior是一个可以控制BottomSheet弹出窗口显示隐藏的Behavior。它可以用于各种布局中,例如CoordinatorLayout、ConstraintLayout等。BottomSheetBehavior有三种状态:collapsed、half-expanded、expanded。在collapsed状态下,BottomSheet的高度仅显示peekHeight(预览高度);在half-expanded状态下,BottomSheet的高度显示peekHeight和half-expandedHeight的高度;在expanded状态下,BottomSheet的高度将展开到整个屏幕。
如果你想要在BottomSheetBehavior全展开状态RecyclerView向下滑动时带动BottomSheetBehavior,你需要重写RecyclerView的`onTouchEvent`方法,并获取RecyclerView的滚动距离,根据滚动距离控制BottomSheetBehavior的展开状态。具体实现如下所示:
```java
private float mLastY;
@Override
public boolean onTouchEvent(MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastY = e.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float y = e.getRawY();
float dy = y - mLastY;
mLastY = y;
// RecyclerView向下滑动并且BottomSheet展开状态,控制BottomSheet收缩
if (dy > 0 && isSheetExpanded()) {
int height = getSheetHeight();
if (height >= getPeekHeight()) {
mBottomSheetBehavior.setPeekHeight(height - (int) dy);
}
}
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return super.onTouchEvent(e);
}
// 判断BottomSheet是否展开
private boolean isSheetExpanded() {
return mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED;
}
// 获取BottomSheet高度
private int getSheetHeight() {
return mBottomSheet.getMeasuredHeight();
}
// 获取BottomSheet预览高度
private int getPeekHeight() {
return mBottomSheetBehavior.getPeekHeight();
}
```
在RecyclerView的onTouchEvent方法中,我们根据RecyclerView的滚动方向和当前BottomSheet展开的状态,控制BottomSheet的高度。如果RecyclerView向下滑动并且BottomSheet为全展开状态,则根据RecyclerView的滚动距离控制BottomSheet的高度。最后需要获取BottomSheet的高度和预览高度,以便计算BottomSheet收缩的高度。
阅读全文