Android: How to redraw a graphic element?
Asked Answered
S

2

17

I have created a class RoundIcon which extends View and the class contains setIconImage() method:

public void setIconImage(int imageFromResources) {
    iconImage = BitmapFactory.decodeResource(getResources(), imageFromResources);
    iconWidth = iconImage.getWidth();
    iconHeight = iconImage.getHeight();
    refreshDrawableState();
}

and there is a method onDraw():

@Override
protected void onDraw(Canvas canvas) {

    if(px == 0 || py == 0)
    {
        px = 50;
        py = 50;
    }


    canvas.drawCircle(px, py, circleRadius, circlePaint);
    canvas.save();

    if(iconImage != null)
    {
        int cardinalX = px - iconWidth/2;
        int cardinalY = py - iconHeight/2;
        canvas.drawBitmap(iconImage, cardinalX, cardinalY, iconPaint);
    }

    canvas.restore();
}

The problem is that the function onDraw() doesn't execute each time the method setIconImage() is called from main activity and therefore the icon doesn't change in the user interface.

Does anyone know how to modify the code in order to redraw an image every time the method setIconImage is called?

Siusan answered 19/6, 2009 at 13:0 Comment(0)
R
44

Try calling View.invalidate() instead of View.refreshDrawableState()

Invalidate will tell the view that all of the pixels in the view need to be redrawn, if you are only updating a smaller area of the view look into the invalidate(Rect) overload for a performance boost.

Relativistic answered 19/6, 2009 at 13:58 Comment(0)
E
7

Definitely call invalidate instead of refreshDrawableState(). You might want to check what thread your on and if on a background call postInvalidate().

Emmuela answered 19/6, 2009 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.