Android Bottom Sheet Dialog无法自动全屏,如何设置固定高度?
解决Bottom Sheet Dialog无法自动展开至全屏的问题
嘿,我来帮你搞定这个Bottom Sheet Dialog不能自动展开全屏的问题!你已经设置了STATE_EXPANDED但没效果,主要是因为BottomSheetBehavior默认的展开逻辑会受内容高度和折叠状态的限制,咱们调整几个参数就能解决。
问题分析
你的代码里已经尝试设置了STATE_EXPANDED,但因为布局高度是wrap_content,加上BottomSheetBehavior默认保留了折叠过渡状态,导致Dialog不会自动占满全屏,必须手动拖动。
解决方案
方案1:调整BottomSheetBehavior参数(推荐)
在Activity代码里,获取到bottomSheetBehavior后,添加以下设置,直接指定展开高度并跳过折叠状态:
bottomSheetView = layoutInflater.inflate(R.layout.dialog_bottom_sheet, null) bottomSheetDialog.setContentView(bottomSheetView) val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetView.parent as View) // 获取屏幕高度,用来设置全屏高度 val displayMetrics = resources.displayMetrics val screenHeight = displayMetrics.heightPixels // 设置展开时的高度为屏幕高度(也可以改成你需要的固定数值,比如800dp) bottomSheetBehavior.peekHeight = screenHeight // 跳过折叠状态,直接进入展开模式 bottomSheetBehavior.skipCollapsed = true // 设置状态为展开 bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED bottomSheetDialog.show()
方案2:修改布局文件的高度设置
把你布局里的NestedScrollView高度从wrap_content改成match_parent,让布局填充整个Dialog空间:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeLayoutBottomSheetView" android:layout_width="match_parent" android:layout_height="match_parent" <!-- 这里改为match_parent --> android:background="#f9626263" app:layout_behavior="android.support.design.widget.BottomSheetBehavior" tools:context=".view.activity.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/background_bottom_sheet_dialog" android:orientation="vertical"> <View android:id="@+id/backgroundViewDialog" android:layout_width="match_parent" android:layout_height="match_parent" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="20dp" tools:ignore="UselessParent"> </LinearLayout> </LinearLayout> </android.support.v4.widget.NestedScrollView>
额外说明
如果你不需要全屏,而是想要固定高度(比如屏幕的80%),只需要把peekHeight改成对应的数值即可:
// 设置为屏幕高度的80% bottomSheetBehavior.peekHeight = (screenHeight * 0.8).toInt()
把这两个方案结合起来使用,就能让Dialog自动展开到你想要的高度,不用再手动拖动啦!
内容的提问来源于stack exchange,提问作者user8882642
相关产品推荐
相关产品推荐

