我正在制作类似于 Google play 的布局。我正在使用需要 fragment 的 ViewPager。我现在有点困惑,因为有些网站说 fragment 需要一个空构造函数,但 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;
}
}
那么是否需要在 fragment 中包含一个构造函数,或者我可以省略构造函数吗?
最佳答案
Java 编译器会自动向任何不具有构造函数的类添加默认的无参数构造函数(即您在问题中提到的“空构造函数”)。
以下空类:
public class A {
}
等同于以下具有空主体的无参数构造函数的类:
public class A {
public A() {
}
}
仅当包含具有一个或多个参数的另一个构造函数时,您才需要显式添加一个无参数构造函数,因为在这种情况下,编译器不会为您添加它。
关于java - Android:我应该向 ViewPager 中使用的 fragment 添加一个空构造函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15276904/