Reputation: 18738
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...
Upvotes: 0
Views: 1804
Reputation: 23432
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?
newInstance(GoogleMap)
method most likelySupportMapFragment
, perhaps one optimised for the device or platformBecause 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;
}
Upvotes: 1