Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

user interface - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...