android - SupportMapFragment 或 GoogleMap 为 null

标签 android android-maps-v2 supportmapfragment

设法使代码没有错误,但是在启动时,我总是在 mMap = mapFrag.getMap(); 行处遇到空指针异常

为什么会这样呢?我是否缺少一些导入或一些步骤?我不确定是 SupportMapFragment 还是 GoogleMap 对象导致了问题。

package com.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public class MapFragment extends SherlockMapFragment {

    private GoogleMap mMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = super.onCreateView(inflater, container, savedInstanceState);
        SupportMapFragment mapFrag= (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_map);
        mMap = mapFrag.getMap(); //null pointer is here
        return root;
    }
}

编辑:这是基于此问题here中给出的解决方案的实现的一部分

最佳答案

请注意,您不一定需要使用自定义 Fragment 子类才能使用 Maps V2。如果您的 fragment 只是纯粹的 map ,您可以从 Activity 创建 MapFragmentSupportMapFragment 并在其中进行配置。

您甚至不需要创建某种 SherlockMapFragment 即可让 map 成为基于 ActionBarSherlock 的应用程序的一部分。常规的 SupportMapFragment 工作得很好。

如果您确实希望在 fragment 中拥有更多业务智能,并且如果您使用 ActionBarSherlock,并且相关业务逻辑需要执行与 ActionBarSherlock 相关的操作(例如,向操作栏提供操作项),然后,只有这样您才需要担心拥有某种SherlockMapFragment

我可以确认this gist包含一个有效的 SherlockMapFragment。请注意,它位于 com.actionbarsherlock.app 包中,因为它需要对 ActionBarSherlock 的其余部分进行一些受包保护的访问。

然后您可以对其进行子类化,例如创建 MyMapFragment:

public class MyMapFragment extends SherlockMapFragment {
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getMap() != null) {
      Log.d(getClass().getSimpleName(), "Map ready for use!");
    }
  }
}

您必须在调用 getMap() 的时机上小心一点——太早,它将返回 nullonActivityCreated() 似乎是一个相当安全的时间,尽管您可以自由地进行实验。

然后,您只需在要使用 SupportMapFragment 的任何地方使用 MyMapFragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.commonsware.android.mapsv2.sherlock.MyMapFragment"/>

Here is the complete project包含上述代码。

关于android - SupportMapFragment 或 GoogleMap 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14539929/

相关文章:

android - Lollipop 为 SupportMapFragment 抛出错误签名

android - 每个 Activity 底部的常用按钮或选项卡

android - 在 32 位操作系统中使用最新版本的 aapt 和 adb

android - 在谷歌地图中使用 dragListener 可编辑多边形

android - 使用 Google Maps Android 标记聚类实用程序时控制缩放级别

android-maps-v2 - 如何在其他 Fragment 中重用 SupportMapFragment

gradle - 使用 Robolectric 问题在 Android Studio 中进行 Android 测试

android - Selenium/Appium 1.7.2 测试运行在 Android 5.1 但不是 Android 8.0

Android Room - 插入有效但选择不返回任何值

android - SupportMapFragment 显示为空白(Map Google V2)