2

I am creating a custom view and in the layout file, I set its width to 200dp, and its height to 200dp.

<com.example.baoshuai.mydefineview.MyTextView
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:layout_margin="30dp"
    android:text="Hello,Sunshine"
    android:textAllCaps="false"
    android:paddingTop="40dp"
    android:textAlignment="center"/>

I am using getWidth() or getMeasuredWidth() to get my view's width, the value is not 200dp, but 700dp. Here is where I get the measurements:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.BLUE);
    int width = getWidth();
    int height = getHeight();
    Log.d("get","Width:"+width+" Height:"+height);
    int measuredWidth = getMeasuredWidth();
    int measuredHeight = getMeasuredHeight();
    Log.d("getMeasured","measuredWidth:"+measuredWidth+" measuredHeight:"+measuredHeight);
}

Here is a screenshot:

enter image description here

Daniel
  • 2,355
  • 9
  • 23
  • 30
lbs0912
  • 331
  • 1
  • 3
  • 13

1 Answers1

0
    android:layout_width="300dp"
    android:layout_height="300dp"

Value you are defining is in dp. When you programatically get width and height int width = getWidth(); value is in pixels.

So it's seems different values but are same.

You can check same by applying values in px in layout and displaying it programatically.

Refere https://stackoverflow.com/a/2025541/3817374 to get more information about different units in Android.

Community
  • 1
  • 1
Beena
  • 2,334
  • 24
  • 50