扩展片段的空构造函数 [英] Empty Constructor for Extended Fragment

查看:178
本文介绍了扩展片段的空构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Android开发人员网站每个 fragment必须有一个空的构造函数,所以它可以实例化时恢复其活动的状态。所以在新的示例项目中,它们具有如下的片段实例化:

  public static class PlaceHolderFragment extends Fragment {

public PlaceHolderFragment(){}

...
}


$ b b

这是非必要的(鼓励?)非静态片段类吗?实际上,我不太明白空构造函数如何帮助恢复活动状态。我有许多自定义对话框片段没有空的构造函数,但没有与他们的问题。如果我不为扩展片段提供一个空的构造函数,可能会有什么后果?

解决方案

空的构造函数在片段类中,因为在某些情况下像屏幕旋转,Android系统将调用您的片段的空构造函数重新创建您的片段。

要回答你的问题,你的应用程序将工作,即使你不提供一个空的构造函数,只要你没有任何参数化构造函数在您的片段。这是因为当你不在类中提供任何构造函数时,java编译器会自动添加一个空构造函数。

编译器不会添加空构造函数如果您已经在类中定义了任何参数化构造函数。在这种情况下,如果你知道某人将创建一个没有参数的类的对象,你必须显式地定义一个空的构造函数。这是一个通用的java编译器行为,不是特定于android的。



因为这是一个常见的错误,人们忘记添加默认构造函数,当类中定义的参数化构造函数。所以Android开发人员网站坚持创建空片段的构造函数在更安全的一面。 无论空构造函数是由您生成还是提供,只要它存在于片段中即可。


According to Android developers website, "Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state". So in the new sample projects they have the fragment instantiation like following:

public static class PlaceHolderFragment extends Fragment {

    public PlaceHolderFragment() {}

    ...
}

Is this necessary (encouraged?) for non-static fragment classes? Actually, I don't quite understand how the empty constructor will help restoring the activity state. I have numerous custom dialog fragments without the empty constructor, but there are no issues with them. What are the possible consequences if I don't supply an empty constructor for the extended fragments?

解决方案

It is recommended to have an empty constructor in fragment class, since in some cases like screen rotation, the Android system will invoke your fragment's empty constructor for recreating your fragment.

To answer your question, your app will work even if you don't provide an empty constructor as long as you don't have any parameterized constructor in your fragment. This is because the java compiler will add an empty constructor automatically when you don't provide any constructor in the class.

Compiler will not add an empty constructor automatically if you have defined any parameterized constructor in your class. In this case you must define an empty constructor explicitly if you know that someone will create an object of your class with no arguments. This is generic java compiler behavior, not specific to android only.

Since it is a common mistake that people forget to add default constructor when there are parameterized constructors defined in the class. So the android developer web site insists to create the empty constructor in fragment to be in safer side. It doesn't matter whether the empty constructor is generated or provided by you, as long as it is present in the fragment.

这篇关于扩展片段的空构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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