Kotlin开发中BottomSheet底部弹窗无法完整展示布局如何解决?
问题原因
BottomSheetDialogFragment默认仅以折叠状态展示固定高度的内容,不会自动展开到完全适配布局内容的高度,所以会出现下半部分内容被截断的问题。
修复步骤
1. 修改弹窗布局高度
打开bottomsheetlayout.xml,将根ConstraintLayout的layout_height属性从match_parent改为wrap_content,让布局可以按照内部内容的实际高度计算尺寸。
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:padding="16dp" android:layout_width="match_parent" <!-- 把这里的match_parent改成wrap_content --> android:layout_height="wrap_content">
2. 修改JemputSayaFragment逻辑,设置默认完全展开
在Fragment中重写onViewCreated方法,获取BottomSheetBehavior实例,设置默认展开状态和适配高度,修改后的完整代码如下:
class JemputSayaFragment : BottomSheetDialogFragment() { private lateinit var binding : BottomsheetlayoutBinding private lateinit var bottomsheet : BottomSheetBehavior<View> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = BottomsheetlayoutBinding.inflate(inflater,container,false) binding.numberPicker.minValue = 1 binding.numberPicker.maxValue = 4 return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 获取BottomSheet的容器View val bottomSheetRoot = dialog?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) bottomSheetRoot?.let { rootView -> bottomsheet = BottomSheetBehavior.from(rootView) // 监听布局测量完成事件,获取实际内容高度 rootView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { rootView.viewTreeObserver.removeOnGlobalLayoutListener(this) // 将折叠高度设置为和内容实际高度一致 bottomsheet.peekHeight = rootView.measuredHeight // 默认设置为完全展开状态 bottomsheet.state = BottomSheetBehavior.STATE_EXPANDED // 可选配置:禁止用户拖拽将弹窗收起为半高状态 bottomsheet.isHideable = false } }) } } }
可选补充:禁止折叠行为
如果不需要用户拖拽调整弹窗高度,可以额外添加BottomSheet状态回调,拦截折叠状态:
// 放在上面的onGlobalLayout回调内即可 bottomsheet.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { // 当检测到要进入折叠状态时,强制切回展开状态 if (newState == BottomSheetBehavior.STATE_COLLAPSED) { bottomsheet.state = BottomSheetBehavior.STATE_EXPANDED } } override fun onSlide(bottomSheet: View, slideOffset: Float) {} })
内容的提问来源于stack exchange,提问作者AiHaQ
相关产品推荐
相关产品推荐

