使用带有GoogleMap Activity Android的手势检测器

时间:2016-06-05 10:54:27

标签: android google-maps-android-api-2 gesturedetector

我尝试将自定义手势检测器附加到Android Studio生成的GoogleMap活动中。我已经能够附加OnMapLongClickListener,但我想附加我自己的SimpleOnGestureListener扩展类。下面是我的两个类的代码。是否可以将GestureDetector类与Maps活动一起使用,我将如何进行此操作?

以下是我的手势探测器类的代码

import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;

import java.util.Map;

/**
 * Created by Chris on 5/6/16.
 */
public class MapGestureListener extends SimpleOnGestureListener implements GoogleMap.OnMapLongClickListener {

    public static final String LOG_TAG = MapGestureListener.class.getSimpleName();

    @Override
    public void onLongPress(MotionEvent e) {
        super.onLongPress(e);
        Log.v(LOG_TAG,"Long press detected");
    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        Log.v(LOG_TAG,"Long press detected Map: " +latLng.toString());
    }
}

以下是MapsActivity类的代码

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.*;
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;

public class Main extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener {

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private float mZoomLevel = 18;

    public static final String LOG_TAG = Main.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 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);

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    protected void attachListener() {
        View view = this.findViewById(R.id.main);

        view.setClickable(true);
        view.setFocusable(true);

        GestureDetector.SimpleOnGestureListener gestureListener = new MapGestureListener();
        final GestureDetector gd = new GestureDetector(this, gestureListener);


        mMap.setOnMapLongClickListener((GoogleMap.OnMapLongClickListener) gestureListener);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.v(LOG_TAG,"Touch Event");
                gd.onTouchEvent(motionEvent);
                return false;
            }
        });
    }


    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);

        attachListener();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);

        moveMap(mLastLocation);

    }

    public void moveMap(LatLng loc)
    {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc,mZoomLevel));
    }

    public void moveMap(Location loc)
    {
        double latCoord = loc.getLatitude();
        double longCoord = loc.getLongitude();

        LatLng latLng = new LatLng(latCoord,longCoord);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,mZoomLevel));
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

1 个答案:

答案 0 :(得分:0)

我在以下问题Google Maps Android API v2 - detect touch on map中找到了我的问题的答案。我唯一要改变的是在TouchableWrapper类中,我改为使用GestureDetector而不是简单地输出触摸事件。

以下是我对TouchableWrapper.java的更改:

import android.content.Context;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.FrameLayout;


public class TouchableWrapper extends FrameLayout {

    public static final String LOG_TAG = TouchableWrapper.class.getSimpleName();

    protected GestureDetector.SimpleOnGestureListener mGestureListener;

    private GestureDetectorCompat mDetector;

    public TouchableWrapper(Context context) {

        super(context);

        mGestureListener = new MapGestureListener();
        mDetector = new GestureDetectorCompat(context,mGestureListener);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        mDetector.onTouchEvent(event);

        return super.dispatchTouchEvent(event);
    }
}