Android:我应该为ViewPager中使用的片段添加一个空构造函数

Xan*_*der 8 java android constructor android-fragments android-viewpager

我正在制作一个类似于Google Play的布局.我正在使用需要片段的ViewPager.我现在有点困惑,因为有些网站说片段需要一个空构造函数,但developer.android.com上的示例不包含构造函数.代码就像这样:

public static class DemoObjectFragment extends Fragment {
    public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        // The last two arguments ensure LayoutParams are inflated
        // properly.
        View rootView = inflater.inflate(
                R.layout.fragment_collection_object, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                Integer.toString(args.getInt(ARG_OBJECT)));
        return rootView;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么是否需要在片段中包含构造函数,或者我可以省略构造函数?

Giu*_*lli 10

Java编译器会自动将一个默认的no-args构造函数(在问题中引用的"空构造函数")添加到任何不包含构造函数的类中.

以下空类:

public class A {
}
Run Code Online (Sandbox Code Playgroud)

使用带有空体的no-args构造函数等效于以下类:

public class A {

    public A() {
    }

}
Run Code Online (Sandbox Code Playgroud)

只有在包含具有一个或多个参数的另一个构造函数时,才需要显式添加no-args构造函数,因为在这种情况下,编译器不会为您添加它.