You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android自定义Dialog实现:底部定位及高度设为Fragment的75%

实现底部自定义弹窗(高度为Fragment的75%)

一、使用普通Dialog实现

完全可以用Dialog实现这种底部弹窗,具体步骤如下:

  • 1. 编写自定义弹窗布局
    先创建一个布局文件(比如dialog_custom_bottom.xml),按照你需要的UI结构编写内部控件,根布局可以用LinearLayout或ConstraintLayout。

  • 2. 在Fragment中初始化并配置Dialog
    在Fragment里创建Dialog实例,通过Window属性设置底部定位和高度:

    val dialog = Dialog(requireContext())
    dialog.setContentView(R.layout.dialog_custom_bottom)
    
    val window = dialog.window ?: return
    val windowParams = window.attributes
    
    // 固定在屏幕底部
    windowParams.gravity = Gravity.BOTTOM
    // 宽度铺满屏幕
    windowParams.width = WindowManager.LayoutParams.MATCH_PARENT
    
    // 计算高度为Fragment所在容器的75%
    val fragmentContainer = requireView()
    // 注意:如果Fragment视图还没加载完成,需要监听布局完成事件
    fragmentContainer.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            fragmentContainer.viewTreeObserver.removeOnGlobalLayoutListener(this)
            val containerHeight = fragmentContainer.height
            windowParams.height = (containerHeight * 0.75).toInt()
            window.attributes = windowParams
        }
    })
    
    // 去掉Dialog默认的背景边框,更贴合自定义UI
    window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    
    dialog.show()
    

二、更优方案:使用BottomSheetDialogFragment

官方提供的BottomSheetDialogFragment是专门针对底部弹窗场景设计的组件,自带拖拽收起、屏幕适配等特性,比普通Dialog更易用且体验更好:

  • 1. 创建BottomSheetDialogFragment子类

    class CustomBottomSheet : BottomSheetDialogFragment() {
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            // 加载自定义布局
            return inflater.inflate(R.layout.dialog_custom_bottom, container, false)
        }
    
        override fun onStart() {
            super.onStart()
            // 设置弹窗高度为Fragment容器的75%
            val bottomSheet = (dialog as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) ?: return
            val fragmentContainer = requireView().parent as ViewGroup
            val containerHeight = fragmentContainer.height
            bottomSheet.layoutParams.height = (containerHeight * 0.75).toInt()
        }
    
        // 可选:禁止拖拽收起弹窗
        override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
            val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
            dialog.behavior.isDraggable = false
            return dialog
        }
    }
    
  • 2. 在Fragment中调用显示

    // 在需要触发弹窗的地方调用
    CustomBottomSheet().show(parentFragmentManager, "CustomBottomSheetTag")
    

内容的提问来源于stack exchange,提问作者HaBuiDuc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:05:17