为了能够用一根手指围绕用户360度旋转我的应用程序中的地图(事物口袋妖怪去风格)我想出了以下解决方案。
我在包含地图的整个片段上放置了一个视图,并为其添加了一个onTouchListener,因为地图上没有设置onTouchListener。当用户拖动一根手指时,下面的代码会旋转地图,它实际上工作得很好。
previousMapTouchX = 0.0f;
previousMapTouchY = 0.0f;
coveringView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getX();
float y = motionEvent.getY();
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_MOVE:
Log.e("MAP", "MOVE");
float dx = x - previousMapTouchX;
float dy = y - previousMapTouchY;
// reverse direction of rotation above the mid-line
if (y > coveringView.getHeight() / 2) {
dx = dx * -1 ;
}
// reverse direction of rotation to left of the mid-line
if (x < coveringView.getWidth() / 2) {
dy = dy * -1 ;
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()),
googleMap.getCameraPosition().zoom, MAX_TILT,
googleMap.getCameraPosition().bearing + ((dx + dy) * TOUCH_SCALE_FACTOR)));
googleMap.moveCamera(cameraUpdate);
break;
case MotionEvent.ACTION_DOWN:
Log.e("MAP", "DOWN");
return false;
}
previousMapTouchX = x;
previousMapTouchY = y;
return true;
}
});
然而问题是,虽然我可以旋转地图,但标记变得不可触摸,因为顶部的视图正在消耗所有触摸事件。所以如果检测到MotionEvent.ACTION_DOWN,我添加了一个返回false的case。但是,这也有效,因为用户显然总是在ACTION_MOVE操作之前执行ACTION_DOWN操作,这意味着永远不会到达地图旋转代码。
我遇到了这样一种情况:我可以正确旋转地图,同时无法选择地图标记,也无法选择地图标记,而无法旋转地图。
有人对我如何运作有任何建议吗?如果谷歌地图可以只有一个onTouchListener,那就容易多了。
答案 0 :(得分:1)
您可以禁用所有地图手势,并将覆盖视图中的触摸事件发送到地图视图:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private View mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapView = mapFragment.getView(); // get the map view to dispatch touch events to it
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40, 4), 18));
mMap.addMarker(new MarkerOptions().position(new LatLng(40, 4)).title("My marker"));
mMap.getUiSettings().setAllGesturesEnabled(false); // disable all the map gestures
View coveringView = findViewById(R.id.coveringView);
coveringView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View view, final MotionEvent motionEvent) {
// Do your stuff here
mapView.dispatchTouchEvent(motionEvent); // dispatch the touch event from the covering view to the map view
return true;
}
});
}
}