DialogFragment 是一种特殊的 Fragment,用于管理对话框(Dialog)的生命周期。它结合了 Dialog 的交互特性和 Fragment 的生命周期管理能力,是创建对话框的推荐方式。

DialogFragment 继承自 Fragment:

public class DialogFragment extends Fragment
			implements DialogInterface.OnCancelListener, DialogInterface.OnDismissListener {

}

1 与传统的 Dialog 对比

特性 Dialog DialogFragment
本质 View 组件 特殊的 Fragment
生命周期管理 无生命周期 完整的生命周期(onCreate/onStart/onResume)
状态保存 需手动创建 自动重建(旋转屏幕等)
与宿主(Activity)的耦合度 高,依赖 Activity 的引用 作为 Fragment 对立存在,耦合度低
内存泄漏风险 低,通过 FragmentManager 管理

2 DialogFragment 的生命周期

2.1 创建阶段

创建阶段

注意:必须重写 onCreateDialog()onCreateView()之一,但不能同时重写两者。

2.2 显示、用户交互阶段

显示阶段

2.3 关闭阶段

关闭阶段

2.4 对话框的特有回调

对话框的特有回调

3 核心实现方式

3.1 方式一:通过 onCreateDialog() 创建对话框

需要系统默认样式的对话框(如 AlertDialog)。

class MyDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return AlertDialog.Builder(requireContext())
            .setTitle("提示")
            .setMessage("确定要删除吗?")
            .setPositiveButton("确定") { _, _ ->
                // 处理确定逻辑
            }
            .setNegativeButton("取消", null)
            .create()
    }
}
3.2 方式二:通过 onCreateView() 创建自定义布局

需要自定义复杂 UI 的对话框。

class CustomDialogFragment : DialogFragment() {
    private var _binding: FragmentCustomDialogBinding? = null
    private val binding get() = _binding!!
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCustomDialogBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化视图
        binding.submitButton.setOnClickListener {
            // 处理提交逻辑
            dismiss() // 关闭对话框
        }
    }
    
    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}
3.3 显示 DialogFragment
// 在 Activity/Fragment 中显示
val dialog = MyDialogFragment()
// 作为对话框显示
dialog.show(supportFragmentManager, "dialog_tag")

supportFragmentManager 是一个关键字组件,用于在 Activity 中管理 Fragment(包括 DialogFragment)的添加、移除、替换、查找等。

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐