Skip to content


Using MapView within Fragment under Google Maps Android API v2.0

There is surprisingly little amount of documentation on how to use the MapView from Googla Maps Android API v2. Especially from within a fragment. Below is a quick code example on how to get a MapView up and running inside a fragment (I am not using MapFragment so I can retain some extra control over the view).

** The guide assumes that you know how to use fragments with ViewPager

Relevant documents:


MapFragment.java

public class MapFragment extends Fragment {
	
	MapView m;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, 
			Bundle savedInstanceState) {
		// inflat and return the layout
		View v = inflater.inflate(R.layout.map_fragment, container, false);
		m = (MapView) v.findViewById(R.id.mapView);
		m.onCreate(savedInstanceState);
		
		return v;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		m.onResume();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		m.onPause();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		m.onDestroy();
	}
	
	@Override
	public void onLowMemory() {
		super.onLowMemory();
		m.onLowMemory();
	}
}

Notice that the map’s various life cycle related methods much be called by overriding the default of what a fragment has.

map_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mapView" />

Posted in Android, Java. Tagged with , , , .