When will MeasureSpec.UNSPECIFIED and MeasureSpec.AT_MOST be applied?

To get a full insight please see the article first. The summery is -

  1. When the width or height of the view is a specific number, such as 100px or 100dp, the spec mode of the view is EXACTLY regardless of the measurement mode of the parent container, and the size of the view is the specific number.

  2. When the width or height of view adopts MATCH_PARENT, the spec mode of view is consistent with the measurement mode of parent container. But the value of specSize is different. When the SpecSize of the parent container is UNSPECIFIED, the specSize of the view is 0. When the SpecSize of the parent container is EXACTLY or AT_MOST, the size of the specSize of the view is the remaining space of the parent container.

  3. When the width or height of view is WRAP_CONTENT, if the SpecMode of parent container is EXACTLY or AT_MOST, the measurement mode of view is AT_MOST. When the specMode of parent container is UNSPECIFIED, the measurement mode of view is UNSPECIFIED. The measurement size of view is also affected by the measurement mode of parent container, specifically when the specMode of parent container is UNSPECIFIED. When SpecMode is EXACTLY or AT_MOST, the maximum size of specSize of view cannot exceed the remaining space of the parent container. When the specMode of the parent container is UNSPECIFIED, the size of view is 0. According to the logic of getChildMeasureSpec method, we can summarize the measurement mode of view and parent container, and the relationship between view's own layoutParams as follows:

enter image description here


The basic definition of how a View is sized goes like this:

MeasureSpec.EXACTLY - A view should be exactly this many pixels regardless of how big it actually wants to be.

MeasureSpec.AT_MOST - A view can be this size or smaller if it measures out to be smaller.

MeasureSpec.UNSPECIFIED - A view can be whatever size it needs to be in order to show the content it needs to show.

MeasureSpec.AT_MOST will be applied to views that have been set to WRAP_CONTENT if the parent view is bound in size. For example, your parent View might be bound to the screen size. It's children will be also bound to this size, but it might not be that big. Thus, the parent view will set the MeasureSpec to be AT_MOST which tells the child that it can be anywhere between 0 and screen size. The child will have to make adjustments to ensure that it fits within the bounds that was provided.

In special cases, the bounds do not matter. For example, a ScrollView. In the case of a ScrollView, the height of the child Views are irrelevant. As such, it will supply an UNSPECIFIED to the children Views which tells the children that they can be as tall as they need to be. The ScrollView will handle the drawing and placement for them.

Tags:

Android