0

I konw the difference between getWidth() and getMeasuredWidth(), but I can not understand the difference between MeasureSpec.getSize(widthMeasureSpec) and getWidth(), which width does MeasureSpec.getSize(widthMeasureSpec) get? thx~~

DawnYu
  • 2,278
  • 1
  • 12
  • 14
  • After reading docs: https://developer.android.com/reference/android/view/View.html#getWidth(). I can make a conclusion that MeasureSpec.getSize(widthMeasureSpec) gives us a future size of view. And getWidth() gives a real view size. But it's only my opinion – Skullper May 09 '17 at 10:50

2 Answers2

0

MeasureSpec.getSize(widthMeasureSpec) returns the preferred width or the specified witdth of a view you want to create. This may or may not be the same as getWidth() after the view has been created, as views may change size based on the width of other views, screen orientation etc.

DKIT
  • 3,471
  • 2
  • 20
  • 24
0

Ok lets see.

getMeasuredWidth() returns the width measurement set in onMeasure() via setMeasuredDimension().

getWidth() returns the final width of the view. The Parent view may accept the measurements set in onMeasure (set via setMeasuredDimension()). In which case getWidth and getMeasuredWidth will return the same value. If the Parent view decides that the measurements you set cannot be used, either because it's too big or too small then it will set the final width to something more appropiate. In which case getWidth will have the final valid width and will be different from getMeasuredWidth(). Always use getWidth() in onDraw(). only use getMeasuredWidth() if you want to know if the parent changed the width you previously set in onMeasure().

Finally to explain MeasureSpec.getSize(widthMeasureSpec) you need to understand the following from the official documentation:

If you need finer control over your view's layout parameters, implement onMeasure(). This method's parameters are View.MeasureSpec values that tell you how big your view's parent wants your view to be, and whether that size is a hard maximum or just a suggestion. As an optimization, these values are stored as packed integers, and you use the static methods of View.MeasureSpec to unpack the information stored in each integer. Custom View Components

As you can read from the snippet. WidthMeasureSpec and WeightMeasureSpec are not pixel measurments. To get the actual pixel value use MeasureSpec.getSize():

int width = MeasureSpec.getSize(widthMeasureSpec)

PD:This all applies to the height as well

For more Infomation see my answer here(its not marked as the answer): MeasureSpec returns a 0 value

Osagui Aghedo
  • 330
  • 4
  • 12