背景
dialog根据当前页的内容的多少来适配高度。
红色是
expandedHeight
表示展开高度,吸顶高度,蓝色peekHeight
是弹出高度,大概是在屏幕高度的60%,假设dialog中的内容高度为contentHeight
,那么dialog高度会根据contentHeight的大小出现以下几种情况:
contentHeight > expandedHeight
:dialog的高度会在peekHeight位置,上划会达到expandedHeight。expandedHeight > contentHeight > peekHeight
:dialog高度会在peekHeight,上划后不会达到expandedHeight位置,而是完全显示内容(也就是到达contentHeight位置)。peekHeight > contentHeight
:dialog高度就是内容高度(contentHeight),这个时候由于内容已经全部显示出来了,所以上划是没有效果的,这个位置即是它的弹出高度(peekHeight),也是它的“展开高度”。
所以dialog高度不固定,是因为:如果内容足够多,那么既可以达到弹出高度,上划也可以达到展开高度。如果内容不够多,则以展示全部内容为主。
解决方案
在dialog的onStart中加入以下代码:
override fun onStart() {
super.onStart()
val dialog = dialog
if (dialog != null) {
val bottomSheet =
dialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
bottomSheet.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
}
val view = view
view?.post {
val parent = view.parent as View
val params = parent.layoutParams as CoordinatorLayout.LayoutParams
val behavior = params.behavior
val bottomSheetBehavior = behavior as BottomSheetBehavior<View>?
val display = activity!!.windowManager.defaultDisplay
val height = display.height * 7 / 10
bottomSheetBehavior!!.maxHeight = height
}
}