public class Trees extends FragmentActivity implements GoogleMap.OnMarkerClickListener {

    private GoogleMap mMap;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trees);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMap();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
            mMap.setMyLocationEnabled(true);
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude),17));
        }
    }
}

最佳答案

首先,将片段活动更改为片段。另外,由于MapFragment也是一个片段,所以现在您将拥有嵌套片段。有很多解决方案/黑客可以使用嵌套片段(对于您的情况,它是片段内的映射片段)。但最推荐的方法是动态地将mappfragment添加到fragment中。为此,你必须遵循这些简单的步骤。
首先,您应该在mappfragment.xml中有一个这样的framelayout

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

现在必须在片段中动态添加supportmappfragment
private SupportMapFragment fragment;

在onActivityCreated()中,复制以下代码
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    FragmentManager fm = getChildFragmentManager();

    if (fragment == null) {
        fragment = SupportMapFragment.newInstance();
        fm.beginTransaction().replace(R.id.fl_map, fragment).commit();
    }
}

因为fragmentTransaction需要一些时间,所以您必须在onResume()中初始化映射,如下所示
    @Override
public void onResume() {
    super.onResume();
if (mMap == null)
        mMap = fragment.getMap();
    try {
        if (mMap != null) {
            builder = new LatLngBounds.Builder();
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mMap.getUiSettings().setZoomControlsEnabled(false);
            mMap.getUiSettings().setZoomGesturesEnabled(true);
            mMap.setMyLocationEnabled(true);

            // do whatever you want to do with map
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

也不要忘记在片段的ondetach()中添加此代码
@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class
                .getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

希望这对你有帮助。

10-08 14:04