How to detect a user pan/touch/drag on Android Map v2
作者捕获的是按屏幕200毫秒以上的事件,有点像LongClick,逻辑改改就可以捕获自己想要的事件了,对我来说,其实想捕获“用户移动了地图”的事件,代码如下:
public class MySupportMapFragment extends SupportMapFragment { public View mOriginalContentView; public TouchableWrapper mTouchView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState); mTouchView = new TouchableWrapper(getActivity()); mTouchView.addView(mOriginalContentView); return mTouchView; } @Override public View getView() { return mOriginalContentView; } }
public class TouchableWrapper extends FrameLayout { private float downX = 0; private float downY = 0; private float upX = 0; private float upY = 0; private static final float MOVE_DISTANCE = 40; private UpdateMapAfterUserInterection updateMapAfterUserInterection; public TouchableWrapper(Context context) { super(context); // Force the host activity to implement the UpdateMapAfterUserInterection Interface try { updateMapAfterUserInterection = (MapActivity) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement UpdateMapAfterUserInterection"); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // lastTouched = SystemClock.uptimeMillis(); downX = ev.getX(); downY = ev.getY(); break; case MotionEvent.ACTION_UP: upX = ev.getX(); upY = ev.getY(); float intervalX = Math.abs(upX - downX); float intervalY = Math.abs(upY - downY); if (intervalX > MOVE_DISTANCE || intervalY > MOVE_DISTANCE) { // Update the map updateMapAfterUserInterection.onUpdateMapAfterUserInterection(); } break; } return super.dispatchTouchEvent(ev); } // Map Activity must implement this interface public interface UpdateMapAfterUserInterection { public void onUpdateMapAfterUserInterection(); } }
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="net.jackie.view.MySupportMapFragment"/>
public class MapActivity extends FragmentActivity implements UpdateMapAfterUserInterection { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Implement the interface method public void onUpdateMapAfterUserInterection() { // TODO Update the map now } }