且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

扩展片段的空构造函数

更新时间:2022-10-14 20:37:56

空的构造函数在片段类中,因为在某些情况下像屏幕旋转,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.