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

2019-07-17 15:23发布

Possible Duplicate:
How do I know the map is ready to get used when using the SupportMapFragment?

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

My problem is that getMap() always returns null.

I have tested the call in 3 different points:

  1. onCreate()
  2. onResume()
  3. in a Handler that is called some seconds after the map is already visible on the screen

Here is the 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?

Answer 1:

如CommonsWare在链接的问题指出,问题在创建时仅occures 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
                }
            }
        };


文章来源: Google Play Service - SupportMapFragment.getMap() always returning null [duplicate]