Christopher Francisco
Christopher Francisco

Reputation: 16268

Why is Fragment instantiated through factory method?

As every Android developer knows, everytime you create a custom Fragment you are not suppose to use it's constructor, as the documentation says. So the way to do this is more like the following:

public static BlankFragment newInstance(String param1, String param2) {
    BlankFragment fragment = new BlankFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
public BlankFragment() {
    // Required empty public constructor
}

Is there any particular reason for Fragment to be instantiated through factory method?

Upvotes: 0

Views: 1148

Answers (1)

marcinj
marcinj

Reputation: 49976

This way you can keep all your initialization code in one place, fragments are often used in many activities so such factory method makes sure you will not miss any new added parameter.

Actually you could add constructor to your fragment, and move your newInstance code to it. The problem would be that android would not use it during your fragment recreation, so such constructor could confuse some coders.

On the other hand, if you would like to create parameter less newInstance() factory method that would use setArguments with some init value, then you could not change it to constructor version, because android will call your parameter less constructor during fragment recreation.

you can read some more here:

http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html

Upvotes: 1

Related Questions