Nicolas Moran Nicolas Moran - 6 months ago 19
Android Question

How do I insert MapsActivity into a Fragment Container?

I have this code on the default MapsActivity:

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}


And this on the Navigation Drawer MainActivity

MapsActivity fragment = new MapsActivity();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();


The second code I can manage to make it work with other fragments except the one with Maps.
What could be wrong?

Answer

If you want to control the SupportMapFragment from the Activity, the answer from cricket_007 will work fine.

If you want custom functionality, and you want to keep it in the Fragment, you can create a Fragment that extends SupportMapFragment, for example:

public class MyCustomMapFragment extends SupportMapFragment 
                          implements OnMapReadyCallback {

    private GoogleMap mMap;

    public MyCustomMapFragment () {
    }

    @Override
    public void onResume() {
        super.onResume();

        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {

        if (mMap == null) {
            getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        mMap.getUiSettings().setMapToolbarEnabled(false);
    }

}

Then you can use a FragmentTransaction to replace the container with your custom SupportMapFragment:

MyCustomMapFragment fragment = new MyCustomMapFragment();
FragmentTransaction fragmentTransaction =
        getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Comments