How to show GoogleMap inside ConstraintLayout?

做~自己de王妃 提交于 2019-12-13 15:26:29

问题


I created a new project "MapsActivity". I got my API key from Google, placed the API key in google_maps_API.xml(debug) inside the YOUR_KEY_HERE area. I see in AndroidManifest it's there. Then I go to build/run the app and it crashes.

I didn't even code anything yet.

According to Android Monitor here's the crash report:

 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)

So I click on the MapsActivity.java:24 and it takes me to the following:

[![enter image description here][1]][1]

Remember, I didn't touch any code yet, just created this new project, only added the API key where I was supposed to and clicked build/run and then it crashes. This is all Google created code that crashes.

I looked on StackOverflow and tried changing from getSupportFragmentManager to getChildFragmentManager as people say and it doesn't work.

activity_maps.xml file:

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

What's wrong? What do I have to change?

EDIT:

A tag allows a layout file to dynamically include different layouts at runtime. At layout editing time the specific layout be used is no known. You can choose which layout you would like previewed while editing the layout.

  • < fragment com.google.android.gms.maps.SupportMapFragment...> (Pick Layout)

回答1:


You need to put the Fragment inside the 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>


来源:https://stackoverflow.com/questions/47166503/how-to-show-googlemap-inside-constraintlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!