‘new Fragment()’ vs ‘Fragment.getInstance()’ in Android?

Published on Author Code Father
What is difference between ‘new Fragment()’ and ‘Fragment.getInstance()’ in Android? ‘new Fragment()’ vs ‘Fragment.getInstance()’ in Android?

getInstance() for Fragment instantiation is a familiar design pattern, which encapsulate the creation of the fragment and its arguments. It means basically that the Fragment is responsible on creating its own instance and should be cleaner and safer than calling only new Fragment(), since you can pass additional data/bundle and “force” the user to use this method. Notice that you are still calling new Fragment() in the getInstance() method, it does not replace it.

public static SomeFragment newInstance(int a, boolean b) {
SomeFragment someFragment = new SomeFragment();

Bundle args = new Bundle();
args.putInt("a", a);
args.putBoolean("b",b);
.....
someFragment.setArguments(args);

return someFragment;}

that way you will have only one place you would create the parameters bundle and not every time you want to instantiate the fragment.

Comments

comments