Drawing on canvas onDraw works, drawing onTouchEvent does not

I am cheating on 2D graphics in the Android SDK and I am having problems with what should be a simple example.

I assume that I am simply misunderstanding something fundamental / basic.

public class DrawView extends View {
    Paint paint = new Paint();
    Canvas canvas = new Canvas();

    public DrawView(Context context) {
        super(context);
        paint.setColor(Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
        this.canvas = canvas;
        this.canvas.drawLine(0,0, 500, 500, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("DrawView", "onTouchEvent: " + event.getX() + "," + event.getY() );

        canvas.drawLine(0,500, 500, 0, paint);

        return true;
    }
}

When the application starts, the above code draws one line from 0,0to 500,500. These parts work great.

X1sGt.png

The problem is that the second line is not displayed in the touch event. onTouchEventdefinitely called because I see a message about debugging coordinates in the log.

Can someone point out what stupid thing I'm doing wrong?

+1
source share
3 answers

invalidate() onTouchEvent(), . invalidate() onDraw().

, , , . . - , onDraw(). canvas.drawLine() onTouchevent . , , "".

onTouchEvent() , , . . , , onTouchEvent(), invalidate(). , , , X Y. X Y onTouchEvent(), onDraw(), , , X y.

+7

postInvalidate(). , ( onDraw()).

0

You can declare a bool variable in your class so that you can pass it to your method ondraw()that the user touched, as well as pass X and Y with other float variables to the ondraw()method! But you must vall invalidate in onTouchEvet()order for the system to redraw the canvas with your new orders!

0
source

All Articles