10

Why is it recommended (different sources) not to overload the constructor for Fragments but use static Fragment.newInstance() with passing a Bundle to it?

When you overload a constructor you just explicitly define default one. Than, if your Fragment would be recreated for some reason you use onSaveInstanceState() with subsequent data extracting on onCreate(). The similar situation with using Fragment.newInstance(), the only difference you don't need to create public default constructor.

Am I understanding something wrong? Thank you very much.

4

2 回答 2

31

为什么建议(不同来源)不要重载 Fragments 的构造函数,而是使用静态 Fragment.newInstance() 并将 Bundle 传递给它?

Android 会在配置更改(例如屏幕旋转)时自动重新创建所有未保留的片段,并且它将为此使用零参数构造函数。提供的BundleviasetArguments()保存为实例状态的一部分,并提供给新创建的片段。因此,您只需实现一种方法(工厂方法)而不是三种(非零参数构造函数 onSaveInstanceState() and onViewStateRestored())即可采用您建议的方法。

我理解错了吗?

如果它适合你,那就去吧。正如您所注意到的,工厂方法方法是一种建议,而不是要求。

于 2012-07-22T17:34:09.507 回答
4

最好不要重载该构造函数,因为 Android 可以在需要时杀死您的 Fragments。而且,为了稍后重新创建它们,它将调用非参数构造函数。

要检索参数,只需调用 getArguments()。

getArguments().getInt("myInt", 0);

即使您的 Fragment 被重新创建,参数也将可用。

于 2012-07-22T17:32:49.070 回答