I struggled a bit with the PoPy answer, but in the end I succeeded, and this is what I came up with. This is probably useful for others who are also facing this problem:
public class MyMapFragment extends Fragment { private MapView mMapView; private GoogleMap mMap; private Bundle mBundle; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflatedView = inflater.inflate(R.layout.map_fragment, container, false); try { MapsInitializer.initialize(getActivity()); } catch (GooglePlayServicesNotAvailableException e) { // TODO handle this situation } mMapView = (MapView) inflatedView.findViewById(R.id.map); mMapView.onCreate(mBundle); setUpMapIfNeeded(inflatedView); return inflatedView; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBundle = savedInstanceState; } private void setUpMapIfNeeded(View inflatedView) { if (mMap == null) { mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap(); if (mMap != null) { setUpMap(); } } } private void setUpMap() { mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } @Override public void onResume() { super.onResume(); mMapView.onResume(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onDestroy() { mMapView.onDestroy(); super.onDestroy(); } }
And here is the corresponding res/layout/map_fragment.xml :
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <com.google.android.gms.maps.MapView android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
You can omit the RelativeLayout (and move the xmlns declaration to your new root element, in this case com.google.android.gms.maps.MapView ) if there is only one element in your layout, as in this example.
Jens Kohl Jan 03 '13 at 13:29 2013-01-03 13:29
source share