Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

What are widthMeasureSpec and heightMeasureSpec in Android custom Views?

I have seen a lot of examples of creating custom views and layouts in android. What I've learned from them is that the measure (as said on Android developer's site) method is onMeasure(), which has widthMeasureSpec and heightMeasureSpec as parameters.

  1. What is the actual meaning of those parameters?
  2. What are their initial values?
  3. With what values they are called if the custom view that I am creating is the parent view for my activity?

I am really very confused about these questions.

question from:https://stackoverflow.com/questions/14493732/what-are-widthmeasurespec-and-heightmeasurespec-in-android-custom-views

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

widthMeasureSpec and heightMeasureSpec are compound variables. Meaning while they are just plain old ints, they actually contain two separate pieces of data.

The first part of data stored in these variables is the available space (in pixels) for the given dimension.

You can extract this data using this convenience method:

int widthPixels = View.MeasureSpec.getSize( widthMeasureSpec );

The second piece of data is the measure mode, it is stored in the higher order bits of the int, and is one of these possible values:

View.MeasureSpec.UNSPECIFIED
View.MeasureSpec.AT_MOST
View.MeasureSpec.EXACTLY

You can extract the value with this convenience method:

int widthMode = View.MeasureSpec.getMode( widthMeasureSpec );

You can do some logic, change one or both of these, and then create a new meassureSpec using the last convenience method:

int newWidthSpec = View.MeasureSpec.makeMeasureSpec( widthPixels, widthMode  );

And pass that on down to your children, usually by calling super.onMeasure( widthMeasureSpec, heightMeasureSpec );

In onMeasure() the MeasureSpec pattern serves the purpose of passing in the maximum allowed space your view and it's children are allowed to occupy. It also uses the spec mode as a way of placing some additional constrains on the child views, informing them on how they are allowed to use the available space.

A good example of how this is used is Padding. ViewGroups take the available width and height, and subtract out their padding, and then create a new meassureSpec, thus passing a slightly smaller area to their children.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...