自定义视图,触摸事件无效

时间:2012-09-27 13:35:56

标签: android

我尝试使用TouchEvent创建一个简单的自定义视图。但是,如果我单击n拖动鼠标光标,则不会绘制任何内容。这是我在模拟器上测试TouchEvent的方式吗?或者我应该在真实设备中运行应用程序(它也无法正常工作)。感谢名单

public class TouchEventView extends View {

    private Paint paint = new Paint();
      private Path path = new Path();

      public TouchEventView(Context context, AttributeSet attrs) {
        super(context, attrs);

        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(5f);
      }


      @Override
      protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
      }

      @Override
      public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();

        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
            path.moveTo(eventX, eventY);
            return true;
          case MotionEvent.ACTION_MOVE:
            path.lineTo(eventX, eventY);
            break;
          case MotionEvent.ACTION_UP:
            // nothing to do 
            break;
          default:
            return false;
        }

        // Schedules a repaint.
        invalidate();
        return true;
      }
}

1 个答案:

答案 0 :(得分:0)

我在我的模拟器中尝试了这个代码并且它可以工作,记得在模拟器视图上移动鼠标时按住左键:

    @Override
public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction() & MotionEvent.ACTION_MASK;
    //Log.d("CV", "Action ["+action+"]");
    switch(action) {
        case MotionEvent.ACTION_DOWN : {
            path.moveTo(event.getX(), event.getY());

            break;
        }
        case MotionEvent.ACTION_MOVE : {
            path.lineTo(event.getX(), event.getY());

            break;
        }

    }

    invalidate();
    return true;
}


@Override
protected void onDraw(Canvas canvas) {

    canvas.drawPath(path, myPaint);
}

private void init() {
    myPaint = new Paint();
    myPaint.setStyle(Paint.Style.STROKE);
    myPaint.setColor(Color.CYAN);
}