I’ve also stumbled upon this and found a few advantages to using the arguments Bundle over instance fields:
-
If it’s in a
Bundlethe Android system knows about it and can create and destroy yourFragment(using the mandatory parameterless/default constructor and usual lifecycle methods), and just pass in the arguments bundle again. This way no arguments get lost on a low memory killing spree or the eventual orientation changes (this often hits me on first deploy to a real device after development in the less-rotating emulator). -
You can just pass the extras
Bundleof anActivityas-is to aFragmentembedded in the layout; e.g. I often use this when I have anActivitythat displays aFragment“fullscreen” and needs some ID (orContentProviderURI) to know what to display/do. I sometimes even add more stuff to aBundle(or a copy) before I pass it on, e.g.@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { // not a re-creation final Bundle args = new Bundle(getIntent().getExtras()); args.putInt(CoverImageFragment.BACKGROUND_RESOURCE, android.R.color.black); final Fragment fragment = CoverImageFragment.newInstance(args); getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, fragment) .commit(); } } -
It keeps the way of developing a
Fragmentclose to that of anActivity, i.e.Bundleas “input parameters, no exceptions”.
As for the downsides you mentioned:
-
I think the overhead is minimal because you most likely won’t be querying the
Bundlein a tight loop, so getting your argument data out once inonCreate(),onViewCreate(), etc. isn’t that bad. -
For type-safety,
Bundlehas all the differentgetXXXX()methods, and even overloads to provide a default value if a something is missing/optional 🙂
As for the newInstance() methods, I think of them as an easy way to encapsulate the new and setArguments() calls for my Fragment; I sometimes provide an additional MyFragment newInstance(String singleIdOfWhatToDisplay) that creates both the Bundle and Fragment in one go and returns a ready-to-go Fragment instance.