Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 370
Xander Avatar asked Mar 07 '13 16:03

Xander


2 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.

like image 104
Giulio Piancastelli Avatar answered Oct 30 '22 14:10

Giulio Piancastelli


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.

like image 39
RCB Avatar answered Oct 30 '22 16:10

RCB