【问题标题】:SupportMapFragment return null on Android studioSupportMapFragment 在 Android Studio 上返回 null
【发布时间】:2015-02-19 18:17:29
【问题描述】:

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

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

返回空 我的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>

为什么返回 null?

我搜索并compileSdkVersion 21 导致它。但是如果我改变它 19 仍然返回 null

【问题讨论】:

  • ...所以保持compileSdkVersion21?
  • 是的,我保持在 21

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


【解决方案1】:

getMap() 不保证返回地图实例。使用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
      }
    });
  }
}

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

【讨论】:

  • 感谢您的回答,但是如何使用 getMapAsync(OnMapReadyCallback) 将 java 类绑定到 xml 以获取片段?
  • 我找到了这个developers.google.com/maps/documentation/android/map,但现在我有 setOnMarkerClickListener(this);和 setOnMapClickListener(this);如何使用它们?以前我将它们与 GoogleMaps 对象一起使用
  • onMapReady(GoogleMap)。现在你有一个谷歌地图对象。在此处进行设置。
  • 谢谢。我尝试了您的代码,但这次给出了有关 getSupportFragmentManager() 的错误。无法解析方法
  • 我做了转换并且错误消失了 mMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
猜你喜欢
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
相关资源
最近更新 更多