如何在片段中运行此 API?

Posted

技术标签:

【中文标题】如何在片段中运行此 API?【英文标题】:How to run this API in a Fragment? 【发布时间】: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_
    android:layout_
    tools:context=".ElectionFragment">

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

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

【问题讨论】:

【参考方案1】:

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

XML 文件中

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

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 这是我的概念。我从我的项目中复制了这段代码

以上是关于如何在片段中运行此 API?的主要内容,如果未能解决你的问题,请参考以下文章

如何缓存片段视图

如何从片段中的 JSON 响应中的对象获取数据

如何在地图片段 API v2 布局顶部添加按钮

如何在 JSON 中为 v3 YouTube API 上传构建片段和状态

如何在活动和片段之间传递对象

在“设置”片段中夸大类PreferenceScreen的错误