Implement the custom view to detect multi-touch, by overriding onTouchEvent().
package com.exercise.AndroidMultiTouch;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MultiToucnView extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
final int MAX_NUMBER_OF_POINT = 10;
float[] x = new float[MAX_NUMBER_OF_POINT];
float[] y = new float[MAX_NUMBER_OF_POINT];
boolean[] touching = new boolean[MAX_NUMBER_OF_POINT];
public MultiToucnView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MultiToucnView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MultiToucnView(Context context) {
super(context);
init();
}
void init() {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.WHITE);
}
@Override
protected void onDraw(Canvas canvas) {
for(int i = 0; i < MAX_NUMBER_OF_POINT; i++){
if(touching[i]){
canvas.drawCircle(x[i], y[i], 50f, paint);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = (event.getAction() & MotionEvent.ACTION_MASK);
int pointCount = event.getPointerCount();
for (int i = 0; i < pointCount; i++) {
int id = event.getPointerId(i);
//Ignore pointer higher than our max.
if(id < MAX_NUMBER_OF_POINT){
x[id] = (int)event.getX(i);
y[id] = (int)event.getY(i);
if((action == MotionEvent.ACTION_DOWN)
||(action == MotionEvent.ACTION_POINTER_DOWN)
||(action == MotionEvent.ACTION_MOVE)){
touching[id] = true;
}else{
touching[id] = false;
}
}
}
invalidate();
return true;
}
}
Modify main.xml to include the custom view, com.exercise.AndroidMultiTouch.MultiToucnView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<com.exercise.AndroidMultiTouch.MultiToucnView
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Download the files.
0 Response to "Detect multi-touch (for 10 pointers)"
Post a Comment