如何实现Android中BottomSheetDialog的全屏展示效果
BottomSheetDialog全屏展示调整方案
默认的BottomSheetDialog受内部BottomSheetBehavior的默认参数限制,展开后最高只能占半屏,按以下步骤修改即可实现全屏效果:
完整修改后的自定义Dialog代码
public class BottomSheetDialogBuyPlan extends BottomSheetDialog { public BottomSheetDialogBuyPlan(@NonNull Context context) { super(context); // 提前加载自定义布局 View bottomSheet = getLayoutInflater().inflate(R.layout.layout, null); setContentView(bottomSheet); BottomSheetBehavior<FrameLayout> behavior = getBehavior(); // 设置默认展开状态 behavior.setState(BottomSheetBehavior.STATE_EXPANDED); // 取消默认半高限制,设置收起高度为屏幕完整高度 DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); behavior.setPeekHeight(displayMetrics.heightPixels); // 不需要滑动收起可添加以下代码 // behavior.setDraggable(false); // 修改系统自带BottomSheet容器高度为匹配父布局,避免内部布局被压缩 FrameLayout bottomSheetContainer = getDelegate().findViewById(com.google.android.material.R.id.design_bottom_sheet); if (bottomSheetContainer != null) { ViewGroup.LayoutParams layoutParams = bottomSheetContainer.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; bottomSheetContainer.setLayoutParams(layoutParams); } show(); } @Override public void setOnShowListener(@Nullable OnShowListener listener) { super.setOnShowListener(listener); } }
可选补充:自定义样式取消默认边距/圆角
如果需要去掉弹窗顶部的默认圆角、边距,可在res/values/styles.xml中添加自定义样式:
<style name="FullScreenBottomSheetDialog" parent="Theme.MaterialComponents.Light.BottomSheetDialog"> <item name="bottomSheetStyle">@style/FullScreenBottomSheetStyle</item> <item name="android:statusBarColor">@android:color/transparent</item> <item name="android:windowIsFloating">false</item> </style> <style name="FullScreenBottomSheetStyle" parent="Widget.MaterialComponents.BottomSheet.Modal"> <item name="backgroundTint">@android:color/white</item> <item name="behavior_peekHeight">match_parent</item> <item name="behavior_hideable">true</item> <item name="behavior_skipCollapsed">true</item> </style>
之后修改Dialog构造方法,引入该样式即可:
public BottomSheetDialogBuyPlan(@NonNull Context context) { super(context, R.style.FullScreenBottomSheetDialog); // 其余逻辑保持不变 }
Activity调用逻辑无需修改
原有调用代码可直接沿用:
BottomSheetDialogBuyPlan bottomSheetDialog = new BottomSheetDialogBuyPlan(getContext());
内容的提问来源于stack exchange,提问作者Malo
相关产品推荐
相关产品推荐

