BottomSheetDialogFragment 如何设置高度和禁止滑动(Kotlin)
主要是获取dialog 的BottomSheetBehavior
然后设置 setPeekHeight
和 BottomSheetCallback
.
package com.example.mychartdemo.view import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.coordinatorlayout.widget.CoordinatorLayout import com.example.mychartdemo.R import com.example.mychartdemo.databinding.FragmentBottomTempletFixedBinding import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback import com.google.android.material.bottomsheet.BottomSheetDialogFragment class BottomTempletFixedFragment: BottomSheetDialogFragment() { private lateinit var binding: FragmentBottomTempletFixedBinding // private var mBottomSheetBehavior: BottomSheetBehavior<View>? = null private val mBottomSheetBehaviorCallback: BottomSheetCallback = object : BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { //禁止拖拽, if (newState == BottomSheetBehavior.STATE_DRAGGING) { //设置为收缩状态 mBottomSheetBehavior!!.state = BottomSheetBehavior.STATE_COLLAPSED } } override fun onSlide(bottomSheet: View, slideOffset: Float) {} } override fun onStart() { super.onStart() val dialog = dialog if (dialog != null) { val bottomSheet = dialog.findViewById<View>(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 mBottomSheetBehavior = behavior as BottomSheetBehavior<View>? mBottomSheetBehavior!!.setBottomSheetCallback(mBottomSheetBehaviorCallback) val display = requireActivity().windowManager.defaultDisplay //设置高度 //val height = display.height / 2 val height = display.height / 3* 2 mBottomSheetBehavior!!.peekHeight = height parent.setBackgroundColor(Color.TRANSPARENT) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { //需要设置背景颜色 binding = FragmentBottomTempletFixedBinding.inflate(layoutInflater) return binding.root } }
view布局需要设置背景颜色,不然为透明色
参考:https://blog.csdn.net/a1018875550/article/details/80954244