简体   繁体   English

如何在片段中使用谷歌地图android SDK?

[英]How to use google maps android SDK in a fragment?

I am using android maps sdk and trying to plot a point on it.我正在使用 android maps sdk 并尝试在其上绘制一个点。 I followed the steps as given here I get an NPE saying that my Support Map Fragment is null.我按照这里给出的步骤我得到一个 NPE 说我的支持地图片段为空。 I am guessing this happens due to the fact that I am using view binding and setting the view as binding.getroot() in my main fragment.我猜这是因为我在主片段中使用视图绑定并将视图设置为 binding.getroot() 。

The code where I declared this.我在其中声明的代码。

  SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map_view);
  supportMapFragment.getMapAsync(this::onMapReady);

The XML where I have declared this.我在其中声明的 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"/>

EDIT: Had nothing to do with View binding.编辑:与视图绑定无关。

You should be using <fragment> tag not androidx.fragment.app.FragmentContainerView .您应该使用<fragment>标签而不是androidx.fragment.app.FragmentContainerView FragmentContainerView is just a Container for fragments on which we can add fragments at runtime . FragmentContainerView只是一个片段容器,我们可以在运行时在上面添加片段。 on other hand <fragment> is itself a fragment this why the android:name attribute is there.另一方面<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"
 />

If you using using it a fragment you should be using getChildFragmentManager()如果您使用它作为片段,您应该使用getChildFragmentManager()

  SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_view);

Update -> Yeah sorry i was wrong earlier .更新-> 是的,对不起,我之前错了。 turns out FragmentContainerView does support adding fragment in xml.原来FragmentContainerView确实支持在 xml 中添加片段。 Try the below code.试试下面的代码。

<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" />

Then you can get the map fragment by using #findFragmentByTag .然后您可以使用#findFragmentByTag获取地图片段。

SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag("mapFragment");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM