检测 Android Google 地图上的阻力

Detect drag on Android Google Maps

我正在使用 google 地图 API 开发应用程序。我有一个布尔值可以告诉我是否跟随用户移动。当用户拖动地图时,我想将其设置为 false。但是我该怎么做呢?这是我的代码

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/checkpoint"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:id="@+id/map"/>

在 java class 中我称之为

    mapFragment = new MapFragment();
    getFragmentManager().beginTransaction().add(R.id.map, mapFragment).commit();
    getFragmentManager().executePendingTransactions();

您可以创建自定义根布局,它会侦察到地图片段的触摸事件,并使用它代替您的默认布局 FrameLayout:

public class CustomFrameLayout extends FrameLayout {

    private GestureDetector gestureDetector;
    private IDragCallback dragListener;

    public CustomFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        gestureDetector = new GestureDetector(context, new GestureListener());
    }

    public interface IDragCallback {
        void onDrag();
    }

    public void setOnDragListener(IDragCallback listener) {
        this.dragListener = listener;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        gestureDetector.onTouchEvent(ev);
        return false;
    }

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            //that's when user starts dragging
            if(dragListener != null) {
                dragListener.onDrag();
            }
            return false;
        }
    }
}

========= your_activity_layout.xml:

<com.your.package.CustomFrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/checkpoint"
    android:id="@+id/map"/>

========= YourActivity.java

CustomFrameLayout mapRoot = (CustomFrameLayout) findViewById(R.id.map);
mapRoot.setOnDragListener(this);

.......
@Override
public void onDrag() {
    //reset your flag here
}

旁注: 您知道 FrameLayout 中的 android:name="com.google.android.gms.maps.SupportMapFragment" 属性没用.. 对吗?您通常在 <fragment> xml 元素上指定 android:name 属性。不是布局。