MapFragment显示null,导致googleMaps为null

时间:2016-09-01 16:33:07

标签: java android google-maps-api-2

在MainActivity.java中

try
{
  supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        SupportMapFragment.getMapAsync(this);
  initializeMap();
}catch (Exception e)
{
    e.printStackTrace();
}
MainActivity.java中的onMapReady(GoogleMap googleMap)方法

public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    Context context = this;

    googleMap.setMyLocationEnabled(true);

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location currentLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    latitudeCurr = currentLocation.getLatitude();
    longitudeCurr = currentLocation.getLongitude();
    Toast.makeText(MainActivity.this, "lat "+latitudeCurr+"    long "+longitudeCurr, Toast.LENGTH_SHORT).show();
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    googleMap.getUiSettings().setZoomGesturesEnabled(true);
    googleMap.getUiSettings().setRotateGesturesEnabled(true);

    if ( Build.VERSION.SDK_INT >= 23 &&
            ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return  ;
    }

但是mapFragment变为null。我也尝试过使用

 mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

请帮忙。

1 个答案:

答案 0 :(得分:0)

我用这个来解决它:

SupportMapFragment m = ((SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.map));
m.getMapAsync(this);
在Fragment.java里面,因为我们在这里调用同一片段的子片段,它解决了这个问题。