BottomSheetDialog和BottomSheetDialogFragment固定高度

BottomSheetDialog设置固定高度

在onCreate方法中调用setPeekHeight和setMaxHeight方法即可

class FixedHeightBottomSheetDialog(
    context: Context,
    theme: Int,
    private val fixedHeight: Int
) : BottomSheetDialog(context, theme) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setPeekHeight(fixedHeight)
        setMaxHeight(fixedHeight)
    }

    private fun setPeekHeight(peekHeight: Int) {
        if (peekHeight <= 0) {
            return
        }
        val bottomSheetBehavior = getBottomSheetBehavior()
        bottomSheetBehavior?.peekHeight = peekHeight
    }

    private fun setMaxHeight(maxHeight: Int) {
        if (maxHeight <= 0) {
            return
        }
        window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, maxHeight)
        window?.setGravity(Gravity.BOTTOM)
    }

    private fun getBottomSheetBehavior(): BottomSheetBehavior? {
        val view: View? = window?.findViewById(com.google.android.material.R.id.design_bottom_sheet)
        return view?.let { BottomSheetBehavior.from(view) }
    }
}

BottomSheetDialogFragment固定高度

重写onCreateDialog方法并返回上面的dialog

class FixedHeightBottomSheetDialogFragment : BottomSheetDialogFragment() {
   override fun onCreateView(
       inflater: LayoutInflater,
       container: ViewGroup?,
       savedInstanceState: Bundle?
   ): View? {
       //comment_dialog_layout里面只有一个RecyclerView,id为comment_recycler
       return inflater.inflate(R.layout.comment_dialog_layout, container, false)
   }

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)
       //这个是一个RecyclerView列表
       comment_recycler.layoutManager = LinearLayoutManager(context)
       comment_recycler.adapter = ListAdapter(context!!)
   }

   //重点是这个方法,重写并返回FixedHeightBottomSheetDialog
   override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
       return FixedHeightBottomSheetDialog(context!!, theme, 200.dp2Px())
   }
}

你可能感兴趣的:(BottomSheetDialog和BottomSheetDialogFragment固定高度)