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

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

问题描述

根据 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?

推荐答案

需要对发生的任何事情来调用其中任一片段的静态方法的空构造:

The empty constructor is needed for anything that happens to call either of these static Fragment methods:

public static Fragment instantiate (Context context, String fname)
public static Fragment instantiate (Context context, String fname, Bundle args)

Android框架使用这些方法来创建你的XML布局定义的片段。它恢复时,碎片的活动状态,也将使用它们(例如,在一个方向改变。)

The Android framework uses these methods to create Fragments defined in your XML layouts. It also will use them when restoring a Fragment's Activity state (for example, on an orientation change.)

如果您不定义一个空的构造,与上述方法上面被称为一个,你会得到一个java.lang.InstantiationException。

If you don't define an empty constructor, and one of the aforementioned methods above is called, you'll get a java.lang.InstantiationException.

如果你看一下片段源码code,你会发现这些方法调用片段类的newInstance()方法。这需要一个公共的空构造。

If you look at the Fragment source code, you'll see that these methods call the fragment class' newInstance() method. This requires a public empty constructor.

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

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