将手势检测器与谷歌地图活动Android一起使用



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

这是我的手势检测器类的代码

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) {
    }
}

我在以下问题中找到了问题的答案,谷歌地图Android API v2 - 检测地图上的触摸。我唯一需要更改的是 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);
    }
}

最新更新