我使用的是谷歌地图服务的com.google.android.gms:play-services-maps:7.5.0
版本。当我尝试调用下面的代码时,我得到了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
。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); //error
return inflater.inflate(R.layout.fragment_example_map, container, false);
}
fragment_example_map.xml文件:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.ExampleMap">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
发布于 2015-06-23 06:52:53
您正在尝试在片段存在之前查找该片段。您指出包含该片段的布局是fragment_example_map.xml
。但是,您正在尝试在膨胀布局文件之前找到地图片段。这是行不通的。
除此之外,您似乎正在尝试从另一个片段的onCreateView()
方法中获取映射片段。我不知道您为什么要在这里嵌套片段,因为这似乎会使您的代码更复杂和更脆弱,而没有明显的好处。
发布于 2015-11-16 21:01:45
在片段中使用getChildFragmentManager()
代替getActivity().getSupportFragmentManager()
。
像这样:
SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
发布于 2017-03-21 17:09:29
如果您在片段中使用android:name="com.google.android.gms.maps.MapFragment"
,则使用以下命令更改代码:
MapFragment mapFragment1 = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
mapFragment1.getMapAsync(this);
但是,如果您在片段中使用android:name="com.google.android.gms.maps.SupportMapFragment"
,则使用以下代码:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
https://stackoverflow.com/questions/30991087
复制相似问题