`
lovelease
  • 浏览: 382816 次
社区版块
存档分类
最新评论

Google Map 如何捕获onTouchEvent

阅读更多
当我的项目中需要捕获google map的touch事件时,才发现google没有提供OnTouchListener,在其提供的一些listener中看了一遍也没发现有什么可以替代的,一室查了一番。还好有人实现了该功能,原文链接如下:
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
        }
 }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics