I do not want to use or extend SupportMapFragment
or MapFragment
. I have my own base class with a bunch of code in it.
The documentation clearly states that when someone uses MapView
by itself, all corresponding lifecycle methods (onCreate()
onResume()
etc.) should be called.
Most of the lifecycle methods in a Fragment
are similar to an Activity
but when I switch back and forth between my Fragment
I eventually get an obfuscated NPE in onDestroy()
or in onResume()
methods.
All the samples provided use an Activity
with a MapView
but not a custom Fragment
.
Has someone done that already? Can you provide sample code of a MapView
in your own Fragment
class?
While using a separate
MapView
following two things are of vital importanceI struggled a bit with PoPy's answer but in the end I managed it and here is what I came up with. Probably this is helpful to others which will also come across this issue:
And here is the corresponding
res/layout/map_fragment.xml
:You can omit the
RelativeLayout
(and move the xmlns declartion up to your new root element, in this case thecom.google.android.gms.maps.MapView
) if you have just one element in your layout like in this example.I succeeded in including a MapView (v2) in a custom Fragment itself embedded in a ViewPager. In my case, the MapView is included in the Fragment layout file. I have had to call lifecycle methods on MapView (
onCreate()
calledonCreateView()
from the Fragment), and to call manuallyMapsInitializer.initialize(context)
to avoid aNullPointerException
from class BitmapDescriptorFactory (to get the bitmap for markers). This last trick is strange, and I don't know why the Map system isn't properly initialized itself without this call, maybe it's just a bug in the current version ...In my case I haven't had any
NullPointerException
inonResume()
oronDestroy()
.