下面是一個兩點觸控的案例代碼:
package com.zzj;import android.app.Activity;import android.os.Bundle;import android.view.MotionEvent;public class AndroidTestActivity extends Activity { private float x0, y0; private float x1, y1; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public boolean onTouchEvent(MotionEvent event) { int pointerCount = event.getPointerCount(); int action = event.getAction(); if (pointerCount == 1) { switch (action) { case MotionEvent.ACTION_DOWN: x0 = event.getX(0); y0 = event.getY(0); System.out.println("ACTION_DOWN pointerCount=" + pointerCount); break; case MotionEvent.ACTION_UP: System.out.println("ACTION_UP pointerCount=" + pointerCount); break; case MotionEvent.ACTION_MOVE: System.out.println("ACTION_MOVE pointerCount=" + pointerCount); break; } } if (pointerCount == 2) { switch (action) { case MotionEvent.ACTION_DOWN: x0 = event.getX(0); y0 = event.getY(0); System.out.println("ACTION_DOWN pointerCount=" + pointerCount); break; case MotionEvent.ACTION_UP: System.out.println("ACTION_UP pointerCount=" + pointerCount); break; case MotionEvent.ACTION_MOVE: System.out.println("ACTION_MOVE pointerCount=" + pointerCount); break; case MotionEvent.ACTION_POINTER_1_DOWN: System.out.println("ACTION_POINTER_1_DOWN pointerCount=" + pointerCount); break; case MotionEvent.ACTION_POINTER_1_UP: System.out.println("ACTION_POINTER_1_UP pointerCount=" + pointerCount); break; case MotionEvent.ACTION_POINTER_2_DOWN: System.out.println("ACTION_POINTER_2_DOWN pointerCount=" + pointerCount); break; case MotionEvent.ACTION_POINTER_2_UP: System.out.println("ACTION_POINTER_2_UP pointerCount=" + pointerCount); break; } } return super.onTouchEvent(event); }}
下面是該案例的一些分析要點:1)使用event.getPointerCount()來擷取當前觸控點的個數。並判斷觸控點,來分別對不同的點進行事件處理。
2)使用event.getAction()來擷取當前的事件碼,單點按下、鬆開和移動的事件分別是:MotionEvent.ACTION_DOWN、ACTION_UP、ACTION_MOVE;第二個點按下、鬆開和移動的事件分別是ACTION_POINTER_2_DOWN、 ACTION_POINTER_2_UP、ACTION_MOVE,注意,單點和兩點響應相同的移動事件,即ACTION_MOVE。
3)只有第二個點按下之後,才會響應MotionEvent.ACTION_POINTER_1_DOWN、MotionEvent.ACTION_POINTER_1_UP,初次單擊是不響應這兩個事件碼的。這點切記。
4)通過event.getX(0)、event.getY(0)來擷取第一個點的座標值,通過event.getX(1)、event.getY(1)來擷取第二個點的座標值。如果有更多的點,依次類推。