当Fragment.instantiate优于MyFragment.newInstance或new MyFragment()时 [英] When Fragment.instantiate is preferable over MyFragment.newInstance or new MyFragment()

查看:670
本文介绍了当Fragment.instantiate优于MyFragment.newInstance或new MyFragment()时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审核其他人对ViewPager的实现。他有一个属于每个视图的片段类数组。在getItem(int i)中,他会编写MyFragment.newInstance(),我认为没有问题。但是,查看ViewPager的google doc,他们在他们的示例中使用Fragment.instantiate。除了设置类信息的方式之外,使用实例化而不是调用newInstance(arg)或空构造函数有什么设计优势吗?

I'm code reviewing someone else's implementation of a ViewPager. He has an array of fragment class that belongs to each view. Inside getItem(int i) he would write MyFragment.newInstance() which I see no issue with. However, looking at the google doc for ViewPager, they use Fragment.instantiate in their example. Other than the way the class information is setup, is there any design advantage of using instantiate over calling newInstance(arg) or an empty constructor?

链接:
Fragment.instantiate

推荐答案

instantiate()允许您按名称指定片段,没有编译时静态解析类。

instantiate() allows you to specify a fragment by name, without compile-time static resolution of the class.

当片段名称来自某些运行时源时,例如二进制XML,这很有用:

It's useful when the fragment name comes from some runtime source, such as a binary XML:

<fragment class="com.example.FragmentClass" ...

这是框架实例化布局XML中指定的片段的方式。

This is how the framework instantiates fragments specified in layout XML.

在代码中,最好使用 newInstance()或空构造函数来获取编译时静态类型检查。

In code, it's preferable to use newInstance() or the empty constructor to get compile-time static type checking.

代码 instantiate()引擎盖与使用 newInstance() / empty构造函数实例化时发生的情况没有太大区别,因此不太可能存在显着差异表现。

The code instantiate() does under the hood is not too different from what happens when instantiated with newInstance() / empty constructor so there's unlikely to be a significant difference in performance.

这篇关于当Fragment.instantiate优于MyFragment.newInstance或new MyFragment()时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆