Android onMeasure
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.setBackgroundColor(Color.RED);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//假设设置View的默认宽高最小为100。
int width = measureWidth(100, widthMeasureSpec);
int height = this.getDefaultSize(100, heightMeasureSpec);
//设置最终测量结果。
setMeasuredDimension(width, height);
}
private int measureWidth(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);//解析出模式。
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
break;
//设置了android:layout_width="wrap_content"
case MeasureSpec.AT_MOST:
result = specSize;
break;
//设置了android:layout_width="match_parent"或一个具体的dp/pix值。
case MeasureSpec.EXACTLY:
result = size;
break;
}
return result;
}
}