This has been driving me crazy.
I think I have everything in place but no matter what I do the touches seem to be cancelled before I lift my finger off the view. Even stranger I can draw long horizontal lines but vertical ones are always very short.
I am using a Samsung G SII 2.3.3 but building to 2.1
Ant ideas?
My sample code:
package com.mycompany.myviews;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class CustomView extends View
{
private ArrayList<DrawPoint> points = new ArrayList<DrawPoint>();
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void addPoint(DrawPoint p)
{
points.add(p);
}
public boolean onTouchEvent (MotionEvent event)
{
DrawPoint p = new DrawPoint((int)event.getX(), (int)event.getY());
switch(event.getAction())
{
case android.view.MotionEvent.ACTION_DOWN:
p.start = true;
break;
case android.view.MotionEvent.ACTION_CANCEL:
Log.d("TouchView", "On Touch cancelled.");
break;
}
addPoint(p);
invalidate();
return true;
}
public void onDraw(Canvas c)
{
super.onDraw(c);
Path path = new Path();
for (int i = 0; i < points.size(); i++)
{
DrawPoint currentPoint = points.get(i);
if (currentPoint.start == true)
path.moveTo(currentPoint.p.x, currentPoint.p.y);
else
path.lineTo(currentPoint.p.x, currentPoint.p.y);
}
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(Color.BLACK);
c.drawPath(path, paint);
}
private class DrawPoint
{
public boolean start = false;
public Point p;
DrawPoint(int x, int y)
{
p = new Point(x, y);
}
}
}
UPDATE: OK, I figured this out. Because this view is inside another View some of the touches are being intercepted by the parent or parents.
The solution I have found to be good enough for my needs is to add the following line into the case for ACTION_DOWN :
getParent().requestDisallowInterceptTouchEvent(true);
This then allows my view to get all touches.