您需要在片段中进行地图管理。
我的密码
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
问题是什么?
最佳答案
您正在初始化地图,甚至没有扩大视图。...因此您的mapFrag
为null。
@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;
}