【问题标题】:Google Play Service - SupportMapFragment.getMap() always returning null [duplicate]Google Play 服务 - SupportMapFragment.getMap() 总是返回 null [重复]
【发布时间】:2012-12-28 10:09:33
【问题描述】:

可能重复:
How do I know the map is ready to get used when using the SupportMapFragment?

我目前正在测试新的 Maps API V2,但我真的很难让它正常工作。

我的问题是 getMap() 总是返回 null。

我已经在 3 个不同的点上测试了调用:

  1. onCreate()
  2. onResume()
  3. 在地图已经在屏幕上可见几秒钟后调用的处理程序中

代码如下:

public class MapActivity extends FragmentActivity {

private SupportMapFragment mMapFragment;

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
            setupMap();
}

@Override
protected void onResume() {
    super.onResume();
    setupMap();
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            setupMap();
        }
    }, 5000);
}

private void setupMap() {
    if (getSupportFragmentManager().findFragmentById(R.id.fragment) == null) {
    mMapFragment = CustomMapFragment.newInstance();
        getSupportFragmentManager().beginTransaction()
                .add(R.id.map_wrapper, mMapFragment).commit();
    }
    GoogleMap map = mMapFragment.getMap();
    if (map != null) {
        mMapFragment.getMap().getUiSettings().setZoomControlsEnabled(true);
        mMapFragment.getMap().getUiSettings().setZoomGesturesEnabled(true);
        mMapFragment.getMap().setMyLocationEnabled(true);
    }
}

我做错了什么?

【问题讨论】:

  • 确实很遗憾,我没有通过搜索功能找到这些问题 :( 我将发布我的示例解决方法作为答案。感谢 CommonsWare!
  • 首先,您在什么类型的设备上运行此代码?物理设备或模拟器(可能未安装 Play 服务)。

标签: android android-maps google-play-services


【解决方案1】:

正如 CommonsWare 在链接问题中所述,问题仅在以编程方式创建 SupportMapFragment 而不是 <fragment> XML 标记时出现。

如果以编程方式创建,地图将在onActivityCreated() 调用中可用。所以我的解决方法如下:

mMapFragment = new SupportMapFragment() {
            @Override
            public void onActivityCreated(Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);
                GoogleMap map = mMapFragment.getMap();
                if (map != null) {
                    //Your initialization code goes here
                }
            }
        };

【讨论】:

  • 不应创建非静态内部片段,因为编译器会自动创建构造函数以将外部类作为参数提供给片段。然后在片段重新创建时,您将获得InstantiationException,因为片段没有默认的空构造函数。
  • 你怎么能做到这一点,同时还提供选项?通常我们用 SupportMapFragment.newInstance(options); 实例化;
  • 你不需要选项,因为你会得到变量作为闭包(如果是最终的),不幸的是代码不可用,请参阅 Alexander 评论
  • @AlexanderMironov 我认为,但我已将mMapFragment 设为静态,但仍获得InstantiationException。有什么帮助吗?
猜你喜欢
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多