Android studio 上的 SupportMapFragment return null

SupportMapFragment return null on Android studio

我将我的应用程序 eclipse 移至 android studio。我的代码在 Eclipse 上运行完美,但在 Android studio

mapView = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

return 空 我的xml在这里

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    >
   <com.google.android.gms.ads.AdView
        android:id="@+id/adMob"
        android:layout_width="fill_parent"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/admob_unit_id" />
   <fragment
  android:id="@+id/map"        
  android:layout_width="fill_parent"        
  android:layout_height="fill_parent"        
  class="com.google.android.gms.maps.SupportMapFragment"/>


</LinearLayout>

为什么 return 为空?

我搜索了 compileSdkVersion 21 原因。但是如果我把它改成 19 还是 return null

getMap() 不保证 return 地图实例。使用 getMapAsync(OnMapReadyCallback),一旦地图准备好将调用回调,并且您保证它不会 null。自 Google Play 服务库 v6.5 起可用。

当使用这种方法摆脱你的 mapView 变量时,回调无论如何都会收到一个地图引用。另请注意,SupportMapFragment 不是 MapView 也不是 GoogleMap(我指的是此处命名错误的变量,请注意。)。

编辑: 建议的解决方案:

public class MainActivity extends ActionBarActivity {

  SupportMapFragment mMapFragment;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);
    mMapFragment = getSupportFragmentManager().findFragmentById(R.id.map);

    // etc.
  }

  public void doSomethingWithMap() {
    mMapFragment.getMapAsync(new OnMapReadyCallback() {
      @Override
      public void onMapReady(GoogleMap googleMap) {
        // do whatever you need with the map
      }
    });
  }
}

关键是当你需要访问地图时,你向片段索取它,它会通过回调传递给你。