android - MapFragment 或 MapView getMap() 在 Lollipop 上返回 null

标签 android google-play-services google-maps-android-api-2 android-5.0-lollipop

我已经在 Android 4.x 版本上使用 Google Maps API v2 很长时间了,没有任何问题。现在我在我的 Nexus 设备(5 和 7)上安装了最新的 Lollipop 版本,试图实现应用程序。

我想指出,KitKiat 上一切正常,而我所描述的问题仅在 Lollipop 上出现。

在我的 XML 源代码中,我使用的是 MapFragment(Google Play 服务库版本 6.1.11)。

<fragment android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

在 Java 代码中,我将覆盖 OnPause() 方法以到达 map :

GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

在这一行它抛出 NullPointerException。在调试器中,应用程序能够找到 fragment ,但它无法返回 GoogleMap。我也尝试过使用 MapView。它也抛出空值。 对我来说最奇怪的是 map 加载在应用程序本身上没有问题,但在代码中我无法使用它。

最佳答案

我遇到了完全相同的问题,但这对我有用:

替换这个...

GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

有了这个……

GoogleMap map = getMapFragment().getMap();

然后把这个坏男孩滑进去试一试......

private MapFragment getMapFragment() {
    FragmentManager fm = null;

    Log.d(TAG, "sdk: " + Build.VERSION.SDK_INT);
    Log.d(TAG, "release: " + Build.VERSION.RELEASE);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Log.d(TAG, "using getFragmentManager");
        fm = getFragmentManager();
    } else {
        Log.d(TAG, "using getChildFragmentManager");
        fm = getChildFragmentManager();
    }

    return (MapFragment) fm.findFragmentById(R.id.map);
}

关于android - MapFragment 或 MapView getMap() 在 Lollipop 上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26592889/

相关文章:

android - 如何在 map 上画很多标记

android - 如何在 Google Analytics 上将屏幕作为页面进行跟踪? (使用应用程序数据的网站 View )

android - Google 询问 Google Play 是否需要政策,但我在 list 文件中拥有有效权限?

android-mapview - Google Maps Android API V2检查设备上是否安装了GoogleMaps

java - 从 ViewPager fragment 获取 Google map

android - Kotlin 方法前的加号是什么意思?

java - 如何在 ListView 中保存每个项目的评分?

java - Android Maps v2 上的自定义 Google Maps Engine map ?

android - Android 直播(http 或 httplive)

android - 刚刚发布的 Android 应用程序,Google Play 未登录