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

mro*_*zis 19 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 Services库版本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"/>
Run Code Online (Sandbox Code Playgroud)

在Java代码中,我重写OnPause()方法来到达map:

GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
Run Code Online (Sandbox Code Playgroud)

在这一行,它抛出NullPointerException.在调试器应用程序中能够找到片段,但它无法返回GoogleMap.我也试过使用MapView.它也抛出null.对我来说最奇怪的事情是地图加载没有问题的应用程序本身,但在代码我无法达到它使用它.

Rhi*_*art 60

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

替换这个......

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我希望我能在这个答案上多次+1 (2认同)

Exc*_*ion 13

谷歌现在使用以下方法更方便地获取地图

    myMapFragment.getMapAsync(new OnMapReadyCallback) {
         @Override
         public void onMapReady(GoogleMap googleMap) {
             myMap = googleMap;
         }
    });
Run Code Online (Sandbox Code Playgroud)

  • 在我的案例中,这是正确的答案.接受的答案似乎假设MapFragment为null,根据问题不是这种情况(在问题中MapFragment不为null,但getMap()的返回值为null). (3认同)