2016-06-05 4 views
0

Я пытаюсь подключить пользовательский детектор жестов к действию GoogleMap, созданной Android Studio. Я смог подключить OnMapLongClickListener, но я хочу добавить свой собственный класс, который расширяет SimpleOnGestureListener. Ниже приведен код для моих двух классов. Можно ли использовать класс GestureDetector с активностью Maps, и как я могу это сделать?Использование детектора жестов с активностью GoogleMap Android

Вот код для моего Жест Detector класса

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

    } 
} 

ответ

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

 Смежные вопросы

  • Нет связанных вопросов^_^