onMeasure()

重写之前先了解MeasureSpec的specMode,一共三种类型:

EXACTLY(精确模式):父容器能够计算出自己的大小,一般是设置为match_parent或者固定值的自定义控件。
AT_MOST(至多不超过模式):父容器指定了一个大小, View 的大小不能大于这个值,也就是父容器不能够直接计算出自己的大小,需要先由它所有的子View自己去计算一下自己大小(measureChildren()),然后再去设置该自定义控件自己的大小(setMeasuredDimension)。一般是设置为wrap_content(最大不能超过父控件)。
UNSPECIFIED(不确定模式):父容器不对 view 有任何限制,要多大给多大,多见于ListView、scrollView或GridView等。

如下代码所示,如果模式为Exactly,系统的设定值就会等于size;如果模式为at_most,系统设定的值就会在自身需要的值和size中取最小值

重写onMeasure
可以看出,这里的padding是自己设置到数据中去的,否则padding值并不生效
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;

if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
mPaint.setTextSize(mTextSize);
text = String.valueOf(mCount);
mPaint.getTextBounds(text, 0, text.length(), mBounds);
float textWidth = mBounds.width();
width = (int) (getPaddingLeft() + textWidth + getPaddingRight());
}

if (heightMode == MeasureSpec.EXACTLY)
{
height = heightSize;
} else
{
mPaint.setTextSize(mTextSize);
mPaint.getTextBounds(text, 0, text.length(), mBounds);
float textHeight = mBounds.height(http://www.amjmh.com/v/BIBRGZ_558768/);
height = (int) (getPaddingTop() + textHeight + getPaddingBottom());
}

setMeasuredDimension(width, height);

}

posted @ 2019-09-10 17:11  李艳艳665  阅读(1497)  评论(0编辑  收藏  举报