首页 > 解决方案 > 没有 onCreateView 的片段

问题描述

最近我看到一些关于直接从 Fragment() 扩展片段布局的文章

class ExampleFragment: Fragment(R.layout.example_fragment)

这是否仅代表不包含任何数据和交互的片段,我们何时应该使用此方法

标签: androidandroid-fragmentskotlinfragment-oncreateview

解决方案


这是在androidx.fragment 版本 1.1.0中添加的:

Fragment LayoutId 构造函数:Fragment 的子类现在可以选择调用 Fragment 上的构造函数,该构造函数采用 R.layout ID,指示应用于此 Fragment 的布局,以替代覆盖 onCreateView()。可以在 onViewCreated() 中配置膨胀的布局。

所以从本质上讲,它是覆盖的简写,onCreateView()它只是膨胀布局并返回它,并鼓励一种在onViewCreated()而不是onCreateView().


推荐阅读