Skip to content

Instantly share code, notes, and snippets.

@Nathaniel100
Last active May 14, 2016 03:20
Show Gist options
  • Save Nathaniel100/ab567b42ab89dd980bb394ec35b265be to your computer and use it in GitHub Desktop.
Save Nathaniel100/ab567b42ab89dd980bb394ec35b265be to your computer and use it in GitHub Desktop.
MeasureSpec

MeasureSpec

A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec represents a requirement for either the width or the height. A MeasureSpec is comprised of a size and a mode. There are three possible modes: UNSPECIFIED The parent has not imposed any constraint on the child. It can be whatever size it wants. EXACTLY The parent has determined an exact size for the child. The child is going to be given those bounds regardless of how big it wants to be. AT_MOST The child can be as large as it wants up to the specified size. MeasureSpecs are implemented as ints to reduce object allocation. This class is provided to pack and unpack the <size, mode> tuple into the int.

什么是MeasureSpec呢,MeasureSpec表示父视图对子视图的布局要求,MeasureSpec分为width或height两种,一般在Viewvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec)作为参数出现,每个MeasureSpec又是由size和mode组成,可通过以下方法获得对应的size和mode

int specSize = MeasureSpec.getSize(measureSpec);
int specMode = MeasureSpec.getMode(measureSpec);

mode分为三种模式:

  1. UNSPECIFIED 父视图对子视图没有任何限制,子视图可以是任意的大小
  2. EXACTLY 父视图决定了子视图的大小,子视图将会使用specSize并且忽略自己想要多大
  3. AT_MOST 子视图可以任意大小,但是不能超过specSize Measure使用int实现,直接将size和mode封装在一个int中,用来降低对象分配的开销.

在使用过程中,在onMeasure方法中,我们计算视图想要的大小desiredSize,然后直接使用系统自带的方法View.resoleSize(desiredSize, measureSpec)即可获得获得真实的大小.

void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int desiredWidth = getDesiredWidth();
  int desiredHeight = getDesiredHeight();
  int width = View.resolveSize(desiredWidth, widthMeasureSpec);
  int height = View.resolveSize(desiredHeight, heightMeasureSpec);
  setMeasuredDimension(width, height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment