How to pass variables to custom View before onDraw() is called?

三世轮回 提交于 2019-12-01 14:34:14

What you need to do is add a flag inside your AvatarView that checks if are you going to render this or not in your onDraw method.

sample:

   public class AvatarView extends ImageView {

    private Bitmap body;
    private Bitmap hat;
    private int containerHeight;
    private int containerWidth;
    private boolean isRender = false;

    public AvatarView(Context context) {
        super(context);
        init();
    }

    public AvatarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AvatarView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void setMeasure(int containerWidth, int containerHeight )
    {
        this.containerHeight = containerHeight;
        this.containerWidth = containerWidth;
    }

    private void init() {
        body = BitmapFactory.decodeResource(getResources(), R.drawable.battle_run_char);
        hat = BitmapFactory.decodeResource(getResources(), R.drawable.red_cartoon_hat);
    }

    public void setRender(boolean render)
    {
       isRender = render;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(isRender )
        {
            canvas.drawBitmap(body, x, y, null);
            canvas.drawBitmap(hat, x, y, null);
        }

    }
    }

Now it wont render when you dont call setRender and set it to true. And just call setMeasure to pass the value.

First you need to call setMeasure and after you set the measure you then call setRender(true) and call invalidate() to call the onDraw method to render the images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!