In the visual editor, you can set the width and height of the View.

How do I get the width and height?

I understand you need to use the attrs.get method, but I don’t know which one to select and which parameters to specify as input.

need to get layout_width

 ViewGroup.LayoutParams layoutParams = this.getLayoutParams(); layout_width=layoutParams.width; layout_height=layoutParams.height; 

Not working, I want to get the width and height

  public class ShapeView extends TextView { Paint paint; int layout_width=0,layout_height=0; public ShapeView(Context context, AttributeSet attrs) { super(context, attrs); paint=new Paint(); paint.setColor(Color.BLUE); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ShapeView); paint.setColor(a.getColor(R.styleable.ShapeView_shapeColor, 0xFF000000)); paint.setStyle(Paint.Style.FILL_AND_STROKE); a.recycle(); this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); layout_width = this.getMeasuredWidth(); layout_height = this.getMeasuredHeight(); Log.e("asd",layout_width+" "+layout_height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(layout_width,layout_height,layout_width,paint); } } 

enter image description here

Pointed 50dp height and width

In the code indicated the canvas.drawCircle(50, 50, 50, paint);

As a result, got it, chtoli bug?

  • 50 in the code is not 50dp in markup! - Eugene Krivenja
  • Well, in general, for a start, radius is 50, then the size of the circle is 100 in pixels and the circle turned out to be smaller, because you also need to take into account density - georgehardcore
  • and canvas.getHeight(); returns pixels in height - georgehardcore

2 answers 2

Here's an option:

  view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int height = view.getMeasuredHeight(); int width = view.getMeasuredWidth(); 
  • mapView is what? - Andro
  • this is what you want to measure - georgehardcore
  • in your example, what exactly is not clear at all - georgehardcore
  • this line is view.measure. What is this class - Andro
  • one
    In general, onDraw method you can get the width and height with Canvas - georgehardcore

While the control is not displayed in the container, it knows nothing about its real size, etc. Therefore, nothing in the constructor.

This is how it will work in your case.

 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(getWidth(), getHeight(), getWidth(), paint); } 
  • Well, in fact, to draw with your code and georgehardcore draws, the fact is that you get some kind of semicircle, and the drawing is drawn at the bottom right. Something I don’t understand, why not the bottom left, is that the new architecture - Andro
  • Everything is ok, I figured it out, thank you all) - Andro