【问题标题】:How to show GoogleMap inside ConstraintLayout?如何在 ConstraintLayout 中显示 GoogleMap?
【发布时间】:2017-11-07 20:02:00
【问题描述】:

我创建了一个新项目“MapsActivity”。我从 Google 获得了我的 API 密钥,将 API 密钥放在了 YOUR_KEY_HERE 区域内的 google_maps_API.xml(debug) 中。我在 AndroidManifest 中看到它在那里。然后我去构建/运行应用程序,它崩溃了。

我什至还没有编写任何代码。

根据 Android Monitor,这是崩溃报告:

 Caused by: 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
                                                 at com.example.mikedouglas.maps.MapsActivity.onCreate(MapsActivity.java:24)

所以我点击了 MapsActivity.java:24,它会将我带到以下内容:

[![在此处输入图片描述][1]][1]

请记住,我还没有接触任何代码,只是创建了这个新项目,只在我应该添加的 API 密钥并单击构建/运行,然后它崩溃了。这是 Google 创建的所有崩溃代码。

我查看了 StackOverflow 并尝试按照人们所说的从 getSupportFragmentManager 更改为 getChildFragmentManager,但它不起作用。

activity_maps.xml 文件:

<android.support.constraint.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
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"
tools:context="com.example.mikedouglas.maps.MapsActivity" />

怎么了?我需要改变什么?

编辑:

标签允许布局文件在运行时动态包含不同的布局。在布局编辑时,使用的具体布局是未知的。您可以在编辑布局时选择要预览的布局。

  • (选择布局)

【问题讨论】:

  • activity_maps.xml 中显示您拥有的内容(作为文本,而不是图像)
  • 我认为您在 xml 文件中寻找 android:name="com.google.android.gms.maps.SupportMapFragment"。
  • 你在里面把 Fragment 改成 ContraintLayout 了吗?
  • 我只在 activity_maps.xml 文本中从片段更改为 ConstraintLayout,因为我对所有 XML 文件都使用了 ConstraintLayout。

标签: android android-fragments android-mapview android-fragmentactivity mapactivity


【解决方案1】:

你需要把 Fragment 放到 ConstraintLayout 里面:

<android.support.constraint.ConstraintLayout      
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mikedouglas.maps.MapsActivity">

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

【讨论】:

  • 添加片段时出现新错误,我在“编辑”下方的代码中进行了编辑。我能做些什么来消除它?
  • @iBEK 这只是 Android Studio 预览版的渲染问题。 Android Studio 无法渲染 SupportMapFragment,请参见此处:stackoverflow.com/questions/23898992/… 您可以忽略它,因为应用运行时一切都会正常显示。
  • 我的模拟器怎么不显示地图?
  • @iBEK mm,要在枚举器上显示 GoogleMaps,您应该下载包含 google api 的 SDK 映像。检查这个 -> developer.android.com/studio/run/emulator
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2012-05-05
  • 2018-01-28
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多