Q: Best practice for instantiating a new Android Fragment

D: So, I have seen two general practices to instantiate a new Fragment in an application:
Fragment newFragment = new MyFragment();
and
Fragment newFragment = MyFragment.newInstance();
The second option makes use of a static method newInstance() and generally contains the following method.
public static Fragment newInstance() 
{
    MyFragment myFragment = new MyFragment();
    return myFragment;
}
At first I though the main benefit was the fact that I could overload the newInstance() method to give flexibility when creating new instances of a Fragment - but I could also this by creating an overloaded constructor for the Fragment.
The question from myself (and others in my city) have we missed something? What are the benefits of one approach over the other - or is it just good practice? Any input I would be thankful for.

Test Case #22


File ID: #9245510-1-cc


public Fragment getItem(int arg0) {
    MyFragment myFragment = new MyFragment();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0 +1);
    myFragment.setArguments(data);
    return myFragment;
}

  1. I think I'm missing something here, could not you use a constructor here anyway, one that creates the Bundle and calls setArguments() still since it will only be called by your code (and not when Android re-creates your fragment)?
  2. Is there an advantage to using a Bundle here? is not it easier to just set the int value of myFragment straight away? e.g. myFragment.someInt = someInt; return myFragment;
  3. Being FORCED to create a no-argument constructor for fragments is potentially the single biggest gotcha in all of programming, anywhere. It forces a complete paradigm shift in object creation and initialization. If you are new to Android and have stumbled on this thread, please read the answer above over and over and over again.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: