问题描述
我正在使用android maps sdk并尝试在其上绘制一个点。我按照给定的here步骤 我收到一个NPE的消息,说我的支持地图片段为空。我猜这是由于我在主片段中使用视图绑定并将视图设置为binding.getroot()而发生的。
SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map_view);
supportMapFragment.getMapAsync(this::onMapReady);
我在其中声明的XML。
<androidx.fragment.app.FragmentContainerView
android:id="@+id/map_view"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent"/>
编辑: 与View绑定无关。
解决方法
您应该使用<fragment>
标签而不是androidx.fragment.app.FragmentContainerView
。 FragmentContainerView
只是片段的容器,我们可以在运行时在其上添加片段。另一方面,<fragment>
本身就是一个片段,这就是android:name
属性在那里的原因。
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
如果使用片段,则应该使用getChildFragmentManager()
SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_view);
更新->是的,抱歉,我之前输入错了。事实证明FragmentContainerView
确实支持在xml中添加片段。尝试以下代码。
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
class="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/fragmentContainerView"
android:layout_width="match_parent"
android:tag="mapFragment"
android:layout_height="match_parent" />
然后,您可以使用#findFragmentByTag
获取地图片段。
SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag("mapFragment");