【问题标题】:Android - How to add a Google Map to this fragment?Android - 如何将谷歌地图添加到这个片段?
【发布时间】:2016-05-23 20:28:19
【问题描述】:

我想在这个片段中添加一个简单的 GoogleMap。

package se.adrianhansson.runpoint;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private Button buttonStart;
    private View view;

    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_home, container, false);
        buttonStart = (Button) view.findViewById(R.id.buttonHomeStart);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    //public void onButtonPressed(Uri uri) {
    public void onButtonPressed(String string){
        if (mListener != null) {
            //mListener.onFragmentInteraction(uri);
            mListener.onFragmentInteractionHome(string);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    //no more use??
    @Override
    public void onClick(View v) {
        mListener.onFragmentInteractionHome("Clicked");
//        switch (v.getId()) {
//            case R.id.buttonHomeStart:
//                mListener.onFragmentInteractionHome("Clicked start");
//                break;
//        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteractionHome(String string);
    }
}

这是我的 xml

<FrameLayout 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"
    tools:context="se.adrianhansson.runpoint.HomeFragment">

    <!-- TODO: Update blank fragment layout -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/hello_blank_fragment" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:id="@+id/buttonHomeStart"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"
            android:backgroundTint="@color/colorPrimary"
            android:nestedScrollingEnabled="false" />
    </RelativeLayout>

</FrameLayout>

我已经尝试了一百万种不同的方法。我遵循了教程,试图复制和修改我自己的代码(我从一个 Activity 移植过来,但显然这与 i 片段不同)。我遇到各种错误,无论我尝试什么,我的应用程序总是在我所有尝试时崩溃。 所以这里附上了我的片段的“干净的石板”。现在..如何添加谷歌地图?

所以我希望这里有人可以帮助我。如何在我的片段中添加一个简单的 Google 地图作为“背景”?

【问题讨论】:

    标签: android google-maps android-fragments android-studio


    【解决方案1】:

    如果您已激活 Maps API 并从开发者控制台获取密钥,则将 MapView 添加到您当前的片段布局:

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

    然后确保你的 Fragment 实现了这个回调:

    implements OnMapReadyCallback
    

    声明一个全局private MapView mapView;

    如果你需要一个全球 GoogleMap private GoogleMap mMap;

    然后在片段的 onCreateView 中: mapView = (MapView) view.findViewById(R.id.myMapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(this);

    并实现回调方法:

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        final LatLng PERTH = new LatLng(-31.90, 115.86); // Perth, Australia
        Marker mymarker = googleMap.addMarker(new  MarkerOptions().position(PERTH).title("Perth,Australia"));
        mymarker.showInfoWindow();
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PERTH, 16));
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setAllGesturesEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);
    
    }
    

    【讨论】:

    • 非常感谢!地图在后台运行,现在没有崩溃。但是,它似乎加载得很慢,我似乎无法滚动或缩放或与之交互(除了单击红色标记(“Peth,Australia”),它会切换显示标记名称)。
    • 编辑:虽然我似乎可以双击放大。但没有其他控件起作用。
    • 由于我使用不同的 GoogleMap - 在活动中 - 我无法为您提供更多帮助。我只是为您找到了解决方案,如果您使用的是fragment,则使用MapView。当我在给你之前尝试解决方案时,地图确实很慢。如果没有其他人来提供建议,我建议您阅读有关 MapView 的信息。
    • 嗯,这是我得到的最接近的。不完全是我想要的,但答案仍然提供了一种稍微替代的方法。
    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 2012-11-02
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多