谷歌Play业务 - SupportMapFragment.getMap()总是返回null业务、Play、谷歌、null

2023-09-12 09:34:26 作者:摊开伤口任宰割

可能重复:   How我知道地图是准备使用SupportMapFragment时习惯?

我目前正在测试新的地图API V2,但我真的无法得到它的工作correclty。

I am currently testing the new Maps API V2 but I'm really having trouble getting it to work correclty.

我的问题是的GetMap()始终返回null。

My problem is that getMap() always returns null.

我已经测试通话在3个不同点:

I have tested the call in 3 different points:

的onCreate() 在onResume() 在一个被映射后,叫一些秒处理器已经显示在屏幕上

下面是code:

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);
    }
}

什么,我做错了什么?

Anything that I'm doing wrong?

推荐答案

由于CommonsWare在链接的问题指出,问题只是创建 SupportMapFragment 编程而不是当occures <片断> XML标记

As CommonsWare stated in the linked question, the problem only occures when creating the SupportMapFragment programmatically and not a <fragment> XML tag.

如果创建的对象,该地图将在 onActivityCreated()通话使用。所以我的解决方法如下:

If created programmatically, the map will be available in the onActivityCreated() call. So my workaround is the following:

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