这一直让我发疯。
我想我已经准备好了一切,但无论我做什么,在我将手指从视野中抬起之前,触摸似乎都被取消了。更奇怪的是,我可以画很长的水平线,但垂直线总是很短。
我正在使用三星 G SII 2.3.3,但构建到 2.1
蚂蚁的想法?
我的示例代码:
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);
}
}
}
更新:好的,我想通了。因为这个视图在另一个视图中,所以一些触摸被父级或父级拦截。
我发现足以满足我的需求的解决方案是将以下行添加到 ACTION_DOWN 的案例中:
getParent().requestDisallowInterceptTouchEvent(true);
这让我的观点得到了所有的触动。