Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to redraw a graphic element?

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?

like image 646
Niko Gamulin Avatar asked Jun 19 '09 13:06

Niko Gamulin


People also ask

How do I force redraw a view?

Invoking invalidate() on a View causes it to draw itself via the View. You should check this out: http://developer.android.com/guide/topics/ui/custom-components.html. A TextView internally invalidates itself when you invoke setText() and redraws itself with the new text set via the setText() call.

How do you refresh a layout?

Android provides a widget that implements the swipe-to-refresh design pattern, which allows the user to trigger an update with a vertical swipe. This is implemented by the SwipeRefreshLayout widget, which detects the vertical swipe, displays a distinctive progress bar, and triggers callback methods in your app.


2 Answers

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.

like image 67
snctln Avatar answered Sep 27 '22 21:09

snctln


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

like image 25
hacken Avatar answered Sep 27 '22 22:09

hacken