【问题标题】:Google map is null谷歌地图为空
【发布时间】:2014-04-19 20:15:28
【问题描述】:

我可以建立一个谷歌地图的实例并查看地图,但我不能 getMap(),它总是为空:

mMapFragment = SupportMapFragment.newInstance();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        fragmentTransaction.replace(R.id.container, mMapFragment);
        fragmentTransaction.commit();
        if (mMap == null) {
            mMap = mMapFragment.getMap();
                    // always null, why?
            if (mMap != null) {
                mMap.getUiSettings().setMyLocationButtonEnabled(true);
            }
        }

【问题讨论】:

  • 替换 Fragment 是异步的,因此该 Fragment 可能尚未放置在您的布局中,因此使 getMap 为您提供 null。在此 mapFragment 事务结束后,您应该使用 getMap 方法替换/添加您的 mapFragment 和地图请求

标签: android google-maps


【解决方案1】:
This works pretty well for me ...
It seems like it's the default background (which is black) of SurfaceView which is causing this bug .
public class MyMapFragment extends SupportMapFragment() {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  View view = super.onCreateView(inflater, container, savedInstanceState);
  setMapTransparent((ViewGroup) view);
  return view;
 };

 private void setMapTransparent(ViewGroup group) {
  int childCount = group.getChildCount();
  for (int i = 0; i < childCount; i++) {
   View child = group.getChildAt(i);
   if (child instanceof ViewGroup) {
    setMapTransparent((ViewGroup) child);
   } else if (child instanceof SurfaceView) {
    child.setBackgroundColor(0x00000000);
   }
  }
 }

};

【讨论】:

    【解决方案2】:

    当以编程方式创建时,地图将在 onActivityCreated() 中可用。所以,试试这样:

    mMapFragment = new SupportMapFragment() {
            @Override
            public void onActivityCreated(Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);
    
               if (mMap == null) {
                    mMap = this.getMap();
    
                    //other code
            }
        };
    

    在这里查看:How do I know the map is ready to get used when using the SupportMapFragment?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 2017-04-26
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多