4

我尝试使用 TouchEvent 制作一个简单的自定义视图。但是,如果我单击并拖动鼠标光标,则不会绘制任何内容。这是我应该在模拟器上测试 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;
      }
}
4

1 回答 1

1

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

@Override
public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction() & MotionEvent.ACTION_MASK;
    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);
}
于 2012-09-28T08:50:54.437 回答