Java 如何在片段中使用谷歌地图视图? 期望行为

Java 如何在片段中使用谷歌地图视图? 期望行为,java,android,android-fragments,android-mapview,google-maps-api-2,Java,Android,Android Fragments,Android Mapview,Google Maps Api 2,如果它影响到任何答案或建议,我希望在这个应用程序中最终看到的是一个导航UI,其中片段是一个地图。我使用了一个模板以一个导航用户界面开始,它给了我几个Fragments,每个选项卡一个。目前,我正在尝试使用GoogleAPI将MapView放在其中一个片段的内部 当前行为 一般来说,这是行不通的(显然)。我已经启动并运行了一切,但是当我打开带有地图的选项卡时,地图是空白的。没有崩溃,也没有输出错误: I/Google Maps Android API: Google Play services c

如果它影响到任何答案或建议,我希望在这个应用程序中最终看到的是一个导航UI,其中
片段
是一个地图。我使用了一个模板以一个导航用户界面开始,它给了我几个
Fragment
s,每个选项卡一个。目前,我正在尝试使用GoogleAPI将
MapView
放在其中一个
片段的内部

当前行为 一般来说,这是行不通的(显然)。我已经启动并运行了一切,但是当我打开带有地图的选项卡时,地图是空白的。没有崩溃,也没有输出错误:

I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 201516040
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
    Selected remote version of com.google.android.gms.googlecertificates, version >= 4
其他详细信息/故障排除 我知道我的API密钥可以工作,因为我有另一个应用程序,其中的地图可以按预期工作。我怀疑我是否需要第二个API键,但我还是看了看,因为如何创建第二个API键并不太明显,我认为直觉是正确的。我使用的大部分代码都是从那个工作示例中复制的;主要区别在于其他示例使用了
SupportMapFragment
,并且它具有
类MapsActivity extends FragmentActivity
。在这里,因为我不想处理嵌套片段,所以我尝试在片段内部使用
MapView

我的代码中没有被复制的部分主要来自在线资源。我所做的一切都没有产生更好的效果

回答一个不同的问题

只包含我已经拥有的东西

让我想到使用
MapsInitializer.initialize(this.getActivity())但这没有帮助

没有什么新鲜事

使用
片段
而不是
地图视图

我还知道正在调用
onMapReady
。在里面,我移动相机,随后调用
onCameraMoveStarted
。但是,它不会输入
onCameraMove
onCameradle

代码 这就是代码,它使用了上面链接中的一些想法。我试图删掉任何不相关的东西(其他碎片等)

AndroidManifest.xml
最后,我在一篇评论中找到了答案


基本上,似乎有些陈腐的东西。在不更改任何代码的情况下,我卸载了该应用程序,清理了构建,重新构建,然后就成功了。

最后,我在一条评论中找到了答案


基本上,似乎有些陈腐的东西。在不更改任何代码的情况下,我卸载了该应用程序,清理了构建,重新构建,然后就成功了。

在我的情况下,我错过了那些mapview的生命周期方法。在我的情况下,我错过了那些mapview的生命周期方法。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.retailtherapy">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateVisible|adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

</manifest>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        tools:context=".MainActivity" />

</androidx.constraintlayout.widget.ConstraintLayout>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_map">

    <fragment
        android:id="@+id/navigation_map"
        android:name="com.example.retailtherapy.ui.map.MapFragment"
        android:label="Map"
        tools:layout="@layout/fragment_map" />

</navigation>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="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=".ui.map.MapFragment" >

    <com.google.android.gms.maps.MapView
        android:id="@+id/googleMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    /*************************************************************************
     *
     * M E M B E R S
     *
     */

    // Location manager for getting current location
    private LocationManager mLocationManager = null;

    // The map object for reference for ease of adding points and such
    private GoogleMap mGoogleMap = null;
    private MapView mMapView = null;

    // The camera position tells us where the view is on the map
    private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition();

    // Current latitude and longitude of user
    private LatLng mCurrentLatLong = new LatLng(0.0, 0.0);

    // These are flags that allow us to selectively not move the camera and
    // instead wait for idle so the movement isn't jerky
    private boolean mCameraMoving = false;
    private boolean mPendingUpdate = false;

    /*************************************************************************
     *
     * F R A G M E N T
     *
     */

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_map, container, false);

        // The google map...
        MapsInitializer.initialize(getActivity());
        mMapView = (MapView) root.findViewById(R.id.googleMap);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this);

        // The required permissions...
        final String[] REQUIRED_PERMISSIONS = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.INTERNET,
        };
        requestPermissions(REQUIRED_PERMISSIONS, 0);

        return root;
    }

    @Override
    public void onStart() throws SecurityException {
        super.onStart();

        // Location manager for getting info current location
        mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    /*************************************************************************
     *
     * G O O G L E   M A P S
     *
     */

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

        // Assuming if here that we have permissions okay.  Dangerous sure
        // but I'm lazy...
        mGoogleMap.setMyLocationEnabled(true);

        // Store the location of the camera for UI purposes so we can go
        // back to where we were
        mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                mCameraPosition = mGoogleMap.getCameraPosition();
            }
        });
        mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
            @Override
            public void onCameraMoveStarted(int i) {
                mCameraMoving = true;
            }
        });
        mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                mCameraMoving = false;
                if (mPendingUpdate) {
                    centerCameraOnLocation(false);
                }
            }
        });

        // Start with user centered in view
        centerCameraOnLocation(true);
    }

    /*************************************************************************
     *
     * L O C A T I O N
     *
     */

    @Override
    public void onLocationChanged(Location location) {
        // Store the current location so if we start auto-center but aren't
        // already, we know where to pan to
        LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (!newLatLng.equals(mCurrentLatLong)) {
            mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude());
            centerCameraOnLocation(false);
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    /*************************************************************************
     *
     * M A P   C A M E R A
     *
     */

    /*
     * Updates the camera position based on current state.  If the camera is
     * already moving, then wait.
     */
    private void centerCameraOnLocation(boolean animate) {
        if (mGoogleMap == null) {
            return;
        }

        if (mCameraMoving) {
            mPendingUpdate = true;
            return;
        }

        // Get the CameraPosition to update to based on whether we are auto
        // centering or not.
        if (mCameraPosition == null) {
            mCameraPosition = Constants.GetDefaultCameraPosition();
        }

        // If this is the same as it was before, then don't reset it
        if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) {
            return;
        }

        // Make the update so we can move the camera
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition);

        // Move the camera with or without animation.  The time we don't want
        // animation is when we're setting the position initially
        if (animate) {
            mGoogleMap.animateCamera(cameraUpdate);
        }
        else {
            mGoogleMap.moveCamera(cameraUpdate);
        }
        mPendingUpdate = false;
    }
}