【问题标题】:How to run this API in a Fragment?如何在片段中运行此 API?
【发布时间】:2020-05-13 04:16:28
【问题描述】:

我只是想按照我在 YouTube (https://www.youtube.com/watch?v=boyyLhXAZAQ) 上找到的教程运行 Google Maps API,出于某种原因,我不知道为什么,但它在主要活动中有效,但我无法获得它在与“fragment_election.xml”相关联的名为“ElectionFragment.java”的片段中工作

是不是跟fragment java类的OnCreate/OnCreateView有关?

ElectionFragment.java

package com.example.fypfinaltrial;


import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
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;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;


/**
 * A simple {@link Fragment} subclass.
 */
public class ElectionFragment extends FragmentActivity implements OnMapReadyCallback {

    Location currentLocation;
    FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;

    public ElectionFragment() {
        // Required empty public constructor
    }



    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_election, container, false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_election);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        fetchLastLocation();
    }

    private void fetchLastLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
            return;
        }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    currentLocation = location;
                    Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
                            + " " + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                    SupportMapFragment supportMapFragment = (SupportMapFragment)
                            getSupportFragmentManager().findFragmentById(R.id.google_map);
                    supportMapFragment.getMapAsync(ElectionFragment.this);
                }
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng)
                .title("I Am Here");
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
        googleMap.addMarker(markerOptions);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissisons, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    fetchLastLocation();
                }
                break;
        }
    }
}

这里是 fragment_election.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".ElectionFragment">

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

它与片段中的片段有关吗?

【问题讨论】:

    标签: android google-maps android-fragments


    【解决方案1】:

    如果你想在片段中实现谷歌地图,那么你必须遵循一些不同的过程,这里是在片段中实现谷歌地图的方法。

    XML 文件中

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

    JAVA文件中

     public class ElectionFragment extends Fragment implements OnMapReadyCallback {
        MapView mapView;
        GoogleMap mMap;
        Marker marker;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View view =  inflater.inflate(R.layout.fragment_election, container, false);
            mapView = view.findViewById(R.id.fake_map);
            mapView.getMapAsync(this);
            mapView.onCreate(savedInstanceState);
            mapView.onResume();// needed to get the map to display immediately
            try {
                MapsInitializer.initialize(getActivity().getApplicationContext());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return view;
        }
    
    
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            this.mMap = googleMap;
            LatLng latLng = new LatLng(43.237601,76.884760);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("");
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_icon));
            markerOptions.getPosition();
            marker = mMap.addMarker(markerOptions);
            CameraPosition cameraPosition = CameraPosition.builder()
                    .target(latLng)
                    .zoom(17)
                    //              .bearing(20)
                    .build();
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 2000, null);
        }
    
        @Override
        public void onResume() {
            super.onResume();
            mapView.onResume();
        }
    
        @Override
        public void onPause() {
            super.onPause();
            mapView.onPause();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            mapView.onDestroy();
        }
    
        @Override
        public void onLowMemory() {
            super.onLowMemory();
            mapView.onLowMemory();
        }
    
        }
    

    【讨论】:

    • 嘿,感谢一百万的帮助。 “try { MapsInitializer.initialize(parentActivity.getApplicationContext());”似乎仍然存在问题部分。我的地段的父活动是一个activity_main,它使用导航抽屉连接地段。我不确定在 parentActivity 中放置什么
    • 使用 getActivity().getApplicationContext()..... 忽略 parentActivity 这是我的概念。我从我的项目中复制了这段代码
    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 2014-10-30
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多