Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between 'new Fragment()' and 'Fragment.getInstance()' in Android?

In android programming,

When we add fragment to specific layout,

we can use following code snippet

Fragment fragment = new SampleFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_layout, fragment);
fragmentTransaction.commit();

or

Fragment fragment = SampleFragment.getInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_layout, fragment);
fragmentTransaction.commit();

I cannot understand what is difference between that fragment object define sentence. From some sources, when use 'Fragment.getInstance()' like singleton pattern, pass bundle data to fragment with 'getInstance(Bundle data)' method parameter.

Could you tell me what difference?

like image 974
Jinwoo Kim Avatar asked Dec 19 '25 00:12

Jinwoo Kim


1 Answers

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.

like image 88
Gilad Eshkoli Avatar answered Dec 21 '25 14:12

Gilad Eshkoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!