下面是一个两点触控的案例代码:
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)来获取第二个点的坐标值。如果有更多的点,依次类推。