Search code examples
javaandroideclipsecanvasandroid-sdk-tools

Change colour of canvas via onTouchEvent


I want to change the backgroundcolour of the canvas as soon as the user touches the screen.

This is my onDraw. Here I assign a colour to a variable and then use the colour variable on the canvas. This works perfect.

@Override
    protected void onDraw(Canvas canvas) {

        int backgroundColour = Color.BLACK;
        canvas.drawColor(backgroundColour);
}

This is my onTouchEvent. Here I check if the user touches the screen (I checked this and the switch recognizes that the screen is touched). The variable colourRed is initiated at the top of the document and has the same code as the variable backgroundColour, but with red as colour.

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) {
    case MotionEvent.ACTION_DOWN :
        canvas.drawColor(colourRed);
        invalidate();
        return true;
    }
    return super.onTouchEvent(event);
}

But every time I touch my screen, the app crashes. I know it has something to do with the

canvas.drawColor(colourRed);

but I don't know how to fix the code, so that the background changes colour when the user touches the screen.


Solution

  • Are you storing the canvas object passed in to onDraw() and then using it later in the context of another method? That's not allowed in Android.

    You should just use setBackgroundColor(Color.RED); in onTouchEvent(). Or take a look into State List Drawables to achieve the same effect.