BottomSheetDialog和BottomSheetDialogFragment固定高度

BottomSheetDialog設置固定高度

在onCreate方法中調(diào)用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<View>? {
        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())
   }
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容