【问题标题】:Fragments without onCreateView没有 onCreateView 的片段
【发布时间】:2020-01-24 16:09:21
【问题描述】:

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

class ExampleFragment: Fragment(R.layout.example_fragment)

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

【问题讨论】:

    标签: android android-fragments kotlin fragment-oncreateview


    【解决方案1】:

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

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

    所以本质上它是覆盖onCreateView() 的简写,它只是扩展布局并返回它,并鼓励在onViewCreated() 而不是onCreateView() 中配置视图的风格。

    【讨论】:

    • 如果配置发生变化,那么片段管理器将通过您唯一的空构造函数实例化您的类的新副本,该构造函数会将相同的布局 ID 传递给超构造函数。我认为这没有问题。
    • @Tenfour04 你说得对,谢谢。将更新答案。
    • 是否可以在onviewcreated中实例化数据绑定
    • 覆盖 fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) _binding= FragmentFirstBinding.bind(view)}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多