TouchEvent(8)多点触摸简单示例

多点触摸的常用api

  Android SDK从2.0开始支持多点触摸.

  Android 会对每个触摸点作历史记录.

 

MotionEvent.getPointerCount() 得到有几个触摸点
MotionEvent.getX(int pointerIndex)  得到下标为pointerIndex的触摸点的X
MotionEvent.getY(int pointerIndex) 得到下标为pointerIndex的触摸点的Y
MotionEvent.getHistoricalX(int pointerIndex, int pos) 得到下标为pointerIndex的触摸点的第pos个历史记录的x
MotionEvent.getHistoricalY(int pointerIndex, int pos) 得到下标为pointerIndex的触摸点的第pos个历史记录的y

示例

 1 import android.app.Activity;
 2 import android.os.Bundle;
 3 import android.util.Log;
 4 import android.view.MotionEvent;
 5 
 6 public class MultiTouchActivity extends Activity {
 7 
 8     @Override
 9     protected void onCreate(Bundle savedInstanceState) {
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.activity_multi_touch);
12     }
13 
14     public boolean onTouchEvent(MotionEvent event) {
15         
16         //得到触摸的点数,这里只处理2点
17         if (event.getPointerCount() == 2) {
18             //正在移动时
19             if (event.getAction() == MotionEvent.ACTION_MOVE) {
20                 
21                 //取得记录的历史轨迹数
22                 int historySize = event.getHistorySize();
23                 if (historySize == 0)
24                     return true;
25 
26                 //取得第一个手指当前的y
27                 float currentY1 = event.getY(0);
28                 //取得第一个手指历史上最新的y
29                 float historyY1 = event.getHistoricalY(0, historySize - 1);
30 
31                 //取得第二个手指当前的y
32                 float currentY2 = event.getY(1);
33                 //取得第二个手指历史上最新的y
34                 float historyY2 = event.getHistoricalY(1, historySize - 1);
35 
36                 //计算两个手指间当前y的距离
37                 float distance = Math.abs(currentY1 - currentY2);
38                 
39                 //计算两个手指间历史上最新的那个y的距离
40                 float historyDistance = Math.abs(historyY1 - historyY2);
41 
42                 if (distance > historyDistance) {
43                     Log.d("status", "放大");
44 
45                 } else if (distance < historyDistance) {
46                     Log.d("status", "缩小");
47                 } else {
48                     Log.d("status", "平移");
49                 }
50 
51             }
52         }
53         return true;
54     }
55 }

 

posted @ 2015-09-07 19:23  f9q  阅读(254)  评论(0)    收藏  举报