1. 程式人生 > >簡單靈活解決 Viewgroup巢狀 產生的手勢衝突問題

簡單靈活解決 Viewgroup巢狀 產生的手勢衝突問題

public class SubView1 extends View {

	private static String TAG = SubView1.class.getSimpleName();
	private GestureDetector mGestureDetector;
	private Paint paint = new Paint();

	public SubView1(Context context) {
		super(context);

	}

	public SubView1(Context context, AttributeSet attrs) {
		super(context, attrs);
		// 為mGestureDetector設定監聽器
		mGestureDetector = new GestureDetector(context, new MTouchDetector());
		// 保證能觸發相應的事件
		setFocusable(true);
		setClickable(true);
		setEnabled(true);
		setLongClickable(true);
	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		// 指定寬和高
		setMeasuredDimension(600, 200);
		// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	@Override
	public void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
		canvas.drawColor((Color.parseColor("#FFA07A")));
		canvas.drawText("SubView1", 100, 100, paint);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		int action = event.getAction();

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			// L.i(TAG, "dispatchTouchEvent ACTION_DOWN");
			break;
		case MotionEvent.ACTION_MOVE:
			// L.i(TAG, "dispatchTouchEvent ACTION_MOVE");
			break;
		case MotionEvent.ACTION_UP:
			// L.i(TAG, "dispatchTouchEvent ACTION_UP");
			break;

		default:
			break;
		}

		getParent().requestDisallowInterceptTouchEvent(true); // 先告訴父Viewgroup,不要攔截我我
		mGestureDetector.onTouchEvent(event); // 通過GestureDetector將MotionEvent事件交給監聽器OnGestureListener
		return super.dispatchTouchEvent(event);
	}

	class MTouchDetector extends SimpleOnGestureListener {
		// Touch down時觸發
		public boolean onDown(MotionEvent e) {
			L.i(TAG, "onDown");
			return super.onDown(e);
		}

		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {

			//tan(60°),手勢與垂直方向大於30°,相應子View的onScroll,父Viewgroup的onScroll則不會響應
			if (1.732*Math.abs(distanceX) >= Math.abs(distanceY)) {
				
				L.i(TAG, "不要攔截我");
				getParent().requestDisallowInterceptTouchEvent(true);	// 告訴父Viewgroup不要攔截我,事件我自行處理			
				return true;
				
			} else {

				getParent().requestDisallowInterceptTouchEvent(false);// 告訴父Viewgroup攔截我,響應父Viewgroup的onScroll
				L.i(TAG, "攔截我");
				return false;
			}

		}

		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			L.i(TAG, "onFling");
			return super.onFling(e1, e2, velocityX, velocityY);
		}

		// 雙擊的第二下Touch down時觸發
		public boolean onDoubleTap(MotionEvent e) {
			L.i(TAG, "onDoubleTap");

			return super.onDoubleTap(e);
		}

		public boolean onDoubleTapEvent(MotionEvent e) {

			L.i(TAG, "onDoubleTapEvent");

			return super.onDoubleTapEvent(e);
		}

	}

}
       再定義父ViewGroup