Home » Android » java – Android: Should I add an empty constructor to a fragment used in ViewPager

java – Android: Should I add an empty constructor to a fragment used in ViewPager

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m making a layout, similar to Google play’s. I’m using a ViewPager which requires fragments. I’m getting a little confused now because some sites say that a fragment requires an empty constructor, but the example on developer.android.com doesn’t contain a constructor. There code is just like this:

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;
    }
}

So is it required to include a constructor in a fragment or can I just leave out the constructor?

How to&Answers:

The Java compiler automatically adds a default no-args constructor (which is the “empty constructor” you refer to in the question) to any class that does not feature a constructor.

The following empty class:

public class A {
}

is equivalent to the following class with a no-args constructor with an empty body:

public class A {

    public A() {
    }

}

You are required to explicitly add a no-args constructor only when including another constructor with one or more arguments, because in this case the compiler does not add it for you.

Answer:

If you do not add any constructor then calling a constructor will refer to the super constructor (the same as creating an empty constructor). But if you’ll create any other constructor (not desired with Fragments, do whatever you want to do in onCreate, your fragment will not be always instantiated with it sometimes the system will instantiate the fragment and the empty constructor will be called) than you need to provide also an empty one.