Android中Bottom Sheet高度与父布局关联实现问询
实现BottomSheet Peek高度与CoordinatorLayout自适应关联
要让BottomSheet的初始可见高度(peekHeight)跟随CoordinatorLayout的高度动态适配,无法直接在XML中完成,必须通过代码动态计算并设置,步骤如下:
给CoordinatorLayout添加ID
当前布局里的CoordinatorLayout没有设置ID,先补充上,方便后续获取实例:<androidx.coordinatorlayout.widget.CoordinatorLayout android:id="@+id/main_coordinator" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@id/button_github_emoji" app:layout_constraintBottom_toBottomOf="parent"> <!-- 内部BottomSheet代码不变 --> </androidx.coordinatorlayout.widget.CoordinatorLayout>动态计算并设置Peek高度
在Activity或Fragment的视图初始化完成后,获取CoordinatorLayout的实际高度,再给BottomSheetBehavior设置对应的peekHeight。因为CoordinatorLayout的高度是通过约束动态计算的,必须等布局测量完成后才能拿到准确值,所以用post方法延迟执行:Kotlin示例(Fragment中)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val bottomSheet = view.findViewById<FrameLayout>(R.id.home_screen_bottom_sheet) val coordinatorLayout = view.findViewById<CoordinatorLayout>(R.id.main_coordinator) val behavior = BottomSheetBehavior.from(bottomSheet) // 等CoordinatorLayout完成测量后获取高度 coordinatorLayout.post { // 按需求调整比例,比如设置为CoordinatorLayout高度的90%,模拟MyAirtel/Paytm的效果 val targetPeekHeight = (coordinatorLayout.height * 0.9).toInt() behavior.peekHeight = targetPeekHeight } }Java示例(Activity中)
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); FrameLayout bottomSheet = findViewById(R.id.home_screen_bottom_sheet); CoordinatorLayout coordinatorLayout = findViewById(R.id.main_coordinator); BottomSheetBehavior<FrameLayout> behavior = BottomSheetBehavior.from(bottomSheet); coordinatorLayout.post(() -> { int targetPeekHeight = (int) (coordinatorLayout.getHeight() * 0.9); behavior.setPeekHeight(targetPeekHeight); }); }可选:移除XML中的固定PeekHeight
虽然代码设置的peekHeight会覆盖XML中的值,但为了避免混淆,可以删掉XML里的app:behavior_peekHeight="600dp",或者保留作为默认 fallback。
这样设置后,BottomSheet的初始可见高度会根据CoordinatorLayout的实际高度自适应,适配不同屏幕尺寸,和MyAirtel/Paytm这类App的效果一致。
内容的提问来源于stack exchange,提问作者ARJUN YADAV
相关产品推荐
相关产品推荐

