片段

时间:2017-03-21 08:51:33

标签: java android android-fragments dictionary supportmapfragment

您需要在片段中获取地图管理。

我的代码

public class Fragment1 extends android.support.v4.app.Fragment implements OnMapReadyCallback{

GoogleMap gm;

private void initializeMap() {
    if (gm == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
        mapFrag.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    gm = googleMap;
    setUpMap();
}

public void setUpMap()
{
    Log.d(LOG_TAG,"Map load!");
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    initializeMap();
    return inflater.inflate(R.layout.need_help_view, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

}

错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference

问题是什么?

1 个答案:

答案 0 :(得分:2)

您正在初始化地图,甚至没有让视图膨胀....所以您的mapFrag为空。

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    initializeMap();
    return inflater.inflate(R.layout.need_help_view, container, false);
}

试试这个:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.need_help_view, container, false);
    if (gm == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
        mapFrag.getMapAsync(this);
    }
    return v;
}