MapFragment.getMap()始终返回null

时间:2014-01-02 06:58:19

标签: android google-maps google-maps-android-api-2

mMapFragment.getMap()始终返回null。我从api级别12开始受到支持,所以我使用的是MapFragment而不是SupportMapFragment

public class MFragment extends Fragment {

private static final String MAP_FRAGMENT_TAG = "map";
private GoogleMap mMap;
private MapFragment mMapFragment;
FragmentManager fm;
Context con;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    fm = getFragmentManager();
    con = getActivity();
      // It isn't possible to set a fragment's id programmatically so we set a tag instead and
    // search for it using that.
    mMapFragment = (MapFragment) getFragmentManager()
            .findFragmentByTag(MAP_FRAGMENT_TAG);

    // We only create a fragment if it doesn't already exist.
    if (mMapFragment == null) {
        // To programmatically add the map, we first create a SupportMapFragment.
        mMapFragment = MapFragment.newInstance();

        // Then we add it using a FragmentTransaction.
        FragmentTransaction fragmentTransaction =
               fm.beginTransaction();
        fragmentTransaction.add((R.id.mapframelayout, mMapFragment);  
        fragmentTransaction.commit();
    }

    // We can't be guaranteed that the map is available because Google Play services might
    // not be available.
    setUpMapIfNeeded();
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View v = inflater.inflate(R.layout.dynamic, container, false);
    return v;
}



private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = mMapFragment.getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}

}

任何人都可以告诉它为什么总是返回null? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

问题在于,当执行setUpMapIfNeeded方法时,无法保证地图片段已准备就绪,这在很大程度上取决于设备,我的设备总是没有问题,然后其他设备表现出与你类似的行为描述

解决方法是多次调用setUpMapIfNeeded,该方法实际上是为此类使用而构建的。我在OnCreate()中放置一个调用,在OnResume()中调用另一个调用,并且问题没有再出现在数百个设备上。尝试相同的方法,即在片段中的onResume上添加方法调用。

如果问题仍然存在,我建议切换到SupportMapFragment,看看是否有帮助。