BottomSheet与MapView视差联动时Google Logo隐藏及地图滚动问题
解决BottomSheet展开时MapView中Google Logo被隐藏的视差效果问题
我明白你现在遇到的问题:想给BottomSheet和MapView添加视差滚动效果,但展开BottomSheet时,MapView底部的Google Logo会被移出屏幕,只有折叠状态下能正常显示。结合你的代码和需求,我来帮你分析问题并给出解决方案。
问题原因分析
你当前的自定义CollapseBehavior是通过计算dy = dependency.getTop() - parent.getHeight()来设置MapView父布局的translationY。当BottomSheet完全展开时,这个计算会让MapView向上平移半个屏幕高度,直接导致MapView底部的Google Logo被移出可视区域,这就是Logo消失的核心原因。
解决方案
我们需要修改视差效果的计算逻辑,基于BottomSheet的折叠高度(peekHeight)来控制MapView的平移范围,确保MapView底部始终留在屏幕内,同时保留视差滚动的效果。
调整后的自定义CollapseBehavior代码
public class CollapseBehavior<V extends ViewGroup> extends CoordinatorLayout.Behavior<V>{ public CollapseBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) { if (isBottomSheet(dependency)) { BottomSheetBehavior behavior = ((BottomSheetBehavior) ((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior()); int peekHeight = behavior.getPeekHeight(); // 处理默认peekHeight为-1的情况,计算为屏幕16:9比例高度 final int actualPeek = peekHeight >= 0 ? peekHeight : (int) (((parent.getHeight() * 1.0) / 16.0) * 9.0); // 获取BottomSheet当前的顶部位置 int currentBottomSheetTop = dependency.getTop(); // 计算滑动比例:0代表完全展开,1代表完全折叠 float scrollRatio = Math.max(0f, Math.min(1f, (float) (actualPeek - currentBottomSheetTop) / actualPeek)); // 计算视差平移量:折叠时无平移,完全展开时向上平移peekHeight的一半 // 你可以根据需求调整比例(比如改为actualPeek/3f)来控制视差幅度 float translationY = -scrollRatio * (actualPeek / 2f); ViewCompat.setTranslationY(child, translationY); return true; } return false; } private static boolean isBottomSheet(@NonNull View view) { final ViewGroup.LayoutParams lp = view.getLayoutParams(); if (lp instanceof CoordinatorLayout.LayoutParams) { return ((CoordinatorLayout.LayoutParams) lp) .getBehavior() instanceof BottomSheetBehavior; } return false; } }
额外检查事项
- 确保你的
bottom_sheet布局根视图已正确绑定BottomSheetBehavior:<!-- 在bottom_sheet布局的根布局中添加该属性 --> app:layout_behavior="@string/bottom_sheet_behavior" - 确认
map_rlyt的布局参数为match_parent,没有被其他布局的margin或padding遮挡底部区域 - 测试时可以调整
actualPeek / 2f中的比例值,找到最符合你预期的视差滚动幅度
这样调整后,BottomSheet展开时MapView只会向上移动折叠高度的一半,Google Logo会始终保持在屏幕可视范围内,同时也能实现你想要的平滑视差滚动效果。
内容的提问来源于stack exchange,提问作者narender sharma
相关产品推荐
相关产品推荐

