如何在android studio中修复'Incovertible types'?

时间:2019-06-24 14:29:19

标签: java android android-studio

不可转换的类型;无法将“ android.support.v4.app.Fragment”转换为“ com.google.android.gms.maps.SupportMapFragment”

package com.dhami.ajay.nearby;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

此行给了我不兼容的类型问题:

SupportMapFragment mapFragment =(SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map)

1 个答案:

答案 0 :(得分:1)

您得到的错误意味着ID为“ map”的片段被定义为常规片段。可能是您的片段在布局中缺少android:name="com.google.android.gms.maps.SupportMapFragment"。检查以确保您的XML布局包含以下内容:

<fragment 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"
    android:id="@+id/map"
    tools:context=".MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

侧面说明:

您似乎正在使用Google提供的Tutorial for the Maps SDK for Android。默认情况下,res/layout/activity_maps.xml中应该有确切的片段块,因此除非您修改了布局或实现了自己的布局,否则您不会有任何问题。