Question

In my app I draw a line and want it to move after my finger on the screen. But now the line redraws only when I take my finger off the screen.

What to do?

The line is drawn in SurfaceView in this way:

 canvas.drawLine(0, 0, x_touch, y_touch, paint);

The code of onTouch:

    public boolean onTouchEvent(MotionEvent event) {
         int action = event.getAction() ;
            x_touch = (int) event.getX() ;
            y_touch = (int) event.getY() ;

            if(action == MotionEvent.ACTION_DOWN)
            {                       


            }


        return super.onTouchEvent(event);


    }
Was it helpful?

Solution 3

My problem was solved in the following way:

New Listener:

public class LintListener implements OnTouchListener {

    public LintListener() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction() ;
         //end_game(true);
            x_touch = (int) event.getX() ;
            y_touch = (int) event.getY() ;

        return true;
    }

}

And in on Create:

super.onCreate(savedInstanceState);
MySurfaceView msf = new MySurfaceView(this);
setContentView(msf);
    msf.setOnTouchListener(new LintListener());

OTHER TIPS

You're blocking the drawing thread until the finger is up, since onTouchEvent is called by the drawing thread (UIThread). Whatever you're doing when if(action == MotionEvent.ACTION_DOWN) needs to be done in a separate thread. For example:

if(action == MotionEvent.ACTION_DOWN) {
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Draw your line
        }
    }.start();
}

try this

Path drawPath = new Path();
Paint drawPaint = new Paint();


@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    // TODO Auto-generated method stub
    super.onSizeChanged(w, h, oldw, oldh);
    canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    drawCanvas = new Canvas(canvasBitmap);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub
    float touchX = event.getX();
    float touchY = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        drawPath.moveTo(touchX, touchY);
        break;
    case MotionEvent.ACTION_MOVE:
        drawPath.lineTo(touchX, touchY);
        break;
    case MotionEvent.ACTION_UP:
        drawCanvas.drawPath(drawPath, drawPaint);
        drawPath.reset();
        break;
    default:
        return false;
    }

    invalidate();//this will cause the onDraw() to execute
    return true;
}

  @Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
    canvas.drawPath(drawPath, drawPaint);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top