Tobias
Tobias

Reputation: 5463

Android Fragments - newInstance() vs instantiate() method

Are there any (dis-)advantages to use the instantiate() method for loading new Fragments? Or is it only on personal taste?

Bundle args = new Bundle();
args.puString(...);
args....
Fragment newFragment = Fragment.instantiate(this, fragmentName, args);

vs.

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

Upvotes: 1

Views: 766

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134714

Using newInstance() is preferable if you have arguments that must be provided to the Fragment, as it's easy to see which parameters are needed, and you don't have to worry about creating a bundle and knowing which keys to use.

If your Fragment takes no arguments, then just avoid it altogether and make it with the default constructor, i.e. new MyFragment().

Upvotes: 1

Related Questions