片段实例化之间的区别;

Difference between fragment instantiation;

我想正确理解这些从构造函数获取片段的方法之间的区别:

1

public MyFragment(DataClass data) {
this.dataClass = data;
}

2

public static MyFragment newInstance(DataClass data) {
MyFragment fragment = new MyFragment();
fragment.setDataClass(data);
return fragment;
}

3

public static MyFragment newInstance(DataClass data) {
MyFragment fragment = new MyFragment();

Bundle args = new Bundle();
args.putInt("myData", data.getData());
fragment.setArguments(args);

return fragment;
}

提前致谢。

首先,Fragment 应该只有空构造函数!

请检查documentation,有说明:
每个 片段必须有一个空构造函数...”。

然后检查 this post 以获得很好的解释。

关于选项 ##2 和 3 - 对我来说,两者都是合适的。

通过 Bundle - 上面提到的 post 又说,"This way if detached and re-attached the object state can be stored through the arguments.".

但是如果您每次创建 newInstanceFragment - #2 方法也不错。我使用 #2 方法,因为我不存储创建的片段。