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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With