public
Last active

Sample android-support-v4-googlemaps MapFragment setup

  • Download Gist
MainActivity.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
public class MainActivity extends android.support.v4.app.FragmentActivity {
// Only one MapView instance is allowed per MapActivity,
// so we inflate it in the MainActivity and tie its
// lifetime here to the MainActivity. Package scope
// so we can grab them from different instances of map
// fragments.
//
// The other option was to make them static, but that causes
// memory leaks on screen rotation.
View mMapViewContainer;
MapView mMapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 
// only init fragment the first time onCreate() is called. Even if the Activity is
// killed / recreated, FragmentManager will add the Fragment once the Activity is back.
if( null == savedInstanceState ) {
// do not add to backstack, or user will be able to press back and
// view MainActivity's blank layout with nothing in it.
// In this case, we want the back button to exit the app.
getSupportFragmentManager()
.beginTransaction()
.add( R.id.main_layout, MyMapFragment.newInstance() )
.setTransition( FragmentTransaction.TRANSIT_FRAGMENT_FADE )
.commit();
}
mMapViewContainer = LayoutInflater.from( this ).inflate( R.layout.mapview, null );
mMapView = (MapView)mMapViewContainer.findViewById( R.id.map );
}
}
MyMapFragment.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
public class MyMapFragment extends Fragment {
private View mMapViewContainer;
private MapView mMapView;
 
public static MyMapFragment newInstance() {
MyMapFragment fragment = new MyMapFragment();
 
Bundle args = new Bundle();
// add any necessary args here
fragment.setArguments( args );
 
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView( inflater, container, savedInstanceState );
 
// We can't grab the MapView onCreate() since Fragment#onCreate() is
// called before Activity#onCreate() (where the MapView is created).
// We also can't do it in Fragment#onActivityCreated() since its called
// after Fragment#onCreateView(). So, we grab it every time here.
//
// Yes, its ugly that this fragment has to know that it lives inside
// a MainActivity.
MainActivity mainActivity = (MainActivity) getActivity();
mMapViewContainer = mainActivity.mMapViewContainer;
mMapView = mainActivity.mMapView;
}
 
// your other fragment code
}

Can you post your entire code? I mean the whole project

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.