package net.npaka.touchex;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;
import android.view.MotionEvent;
//タッチイベントの処理
public class TouchView extends View {
private HashMap<String,PointF> points=new HashMap<String,PointF>();
//コンストラクタ
public TouchView(Context context) {
super(context);
setBackgroundColor(Color.WHITE);
setFocusable(true);
}
//描画
@Override
protected void onDraw(Canvas canvas) {
//描画オブジェクトの生成
Paint paint=new Paint();
paint.setAntiAlias(true);
paint.setTextSize(32);
//タッチXY座標の描画
canvas.drawText("MultiTouchEx>",0,40*1,paint);
Object[] keys=points.keySet().toArray();
for (int i=0;i<keys.length;i++) {
PointF pos=(PointF)points.get(keys[i]);
canvas.drawText((int)pos.x+","+(int)pos.y,0,80+40*i,paint);
}
}
//タッチイベントの処理
@Override
public boolean onTouchEvent(MotionEvent event) {
int action=event.getAction();
int count=event.getPointerCount();
int index=(action&MotionEvent.ACTION_POINTER_ID_MASK)>>
MotionEvent.ACTION_POINTER_ID_SHIFT;//API Level 5〜7
//int index=event.getActionIndex();//API Level 8以降
switch (action&MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
points.put(""+event.getPointerId(index),
new PointF(event.getX(),event.getY()));
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
points.remove(""+event.getPointerId(index));
break;
case MotionEvent.ACTION_MOVE:
for (int i=0;i<count;i++) {
PointF pos=points.get(""+event.getPointerId(i));
pos.x=event.getX(i);
pos.y=event.getY(i);
}
break;
}
invalidate();
return true;
}
}
|