سؤال

In the documentation for MapFragment and SupportMapFragment they create a new fragment by calling newInstance() instead of using new SupportMapFragment().

My app project extends SupportMapFragment, and I tried to call MyMapFragment.newInstance() on my fragment class, resulting in the map showing up as expected but none of my overridden methods such as onCreateView() and onActivityCreated() were being called. Took me a while before I tried instantiating my fragment by using new MyMapFragment() instead - and voíla, my overridden methods started getting called!

I didn't override newInstance() in my class, and in hindsight it's obvious that newInstance() returns an instance of SupportMapFragment, not an instance of my extended class (duh!).

But my question is - why is there a newInstance() method and why does the documentation use it, when it seems to work just as well using new SupportMapFragment()? What's the difference of using one or the other? I haven't been able to find the source code for SupportMapFragment, so...

هل كانت مفيدة؟

المحلول

In this case I believe the newInstance method is just a static factory method for the empty constructor so has no effect (though without the source code available we cannot know for sure), i.e. it is probably something like:

public static SupportMapFragment newInstance() {
    return new SupportMapFragment();
}

So why does it exist?

  • For consistency with the other newInstance(GoogleMap) method most likely
  • In theory the method could return a sub-class of SupportMapFragment, perhaps one optimised for the device or platform
  • In case any arguments need to be set (perhaps now or in the future)

Because of the last point, it is generally a good practice to always use static factories when creating fragments, in the future it could be modified to:

public static SupportMapFragment newInstance() {
    SupportMapFragment fragment = new SupportMapFragment();
    Bundle args = new Bundle();
    args.putBoolean("secretOptionNotEnabledWithNormalConstructor", true);
    fragment.setArguments(args);
    return fragment;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top