0

I am trying to set the Width and Height for a customview on which I use Canvas to draw.

Have noticed that onDraw() always sets to a default width and height, and not take the values as specified in layout xml or set using the onMeasure method.

Could some one help me where I am going wrong.

Thanks

@Override
protected void onMeasure(final int widthMeasureSpec,
                         final int heightMeasureSpec) {
     super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
}
Vinay
  • 2,395
  • 3
  • 30
  • 35
NikW
  • 347
  • 1
  • 11
  • There is no shame in google "android change size of view dynamically". It will lead you to this [link](https://stackoverflow.com/questions/2963152/how-to-resize-a-custom-view-programmatically). – Laufwunder Jan 28 '21 at 11:15
  • @Laufwunder Please understand my question first, i need to change width and height on onDraw using canvas. The link which you have suggested will not work in this case. The answer provided in your link is not helpful. Thanks!! – NikW Jan 28 '21 at 13:57
  • Shame on me! sry – Laufwunder Jan 28 '21 at 14:31
  • onDraw is not place to change size of the View – Style-7 Jan 28 '21 at 19:52

1 Answers1

2

you can use this code

public class CustomView extends View{
private Paint paint;
private int w;
private int h;

public CustomView(Context context, AttributeSet attr) {
    super(context, attr);
    paint = new Paint();
    paint.setTextAlign(Align.CENTER);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    this.w = w;
    this.h = h;
    super.onSizeChanged(w, h, oldw, oldh);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.WHITE);
    canvas.drawText("TEST", w/2, h/2, paint);   
}

}

Fahime Zivdar
  • 341
  • 2
  • 9