Java – Android custom view can only call OnDraw once

I made a custom view, which should animate the points on the background according to some external data (like the charm of textviews)

Then add the view to the XML and set Android: background

The view is rendered correctly but not updated Some debugging shows that OnDraw is called only once What's missing?

Code for my custom view:

public class Gmeter extends ImageView {
    private Bitmap dot;
    private float dotHeight,dotWidth;

    public Gmeter(Context context,AttributeSet attrs) {
        super(context,attrs);

        dot = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.g_dot);
        dotWidth = dot.getWidth();
        dotHeight = dot.getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);

        float datax =(float) Data.getX();

        float x = (getWidth()-dotWidth)/2f;
        float y = (getHeight()-dotHeight)/2f;

        x+= datax * getWidth() /2f;

        canvas.drawBitmap(dot,x,y,null);
    }

}

Solution

Regardless of setting X in the data, you need to call invalidate () to tell view that it needs to redraw according to the new data When new data is available, view cannot read your thoughts:)

And certainly connect it with data update... If you call invalidate () from onDraw (), you will have a good way to waste CPU cycles.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>