android怎么可以看到重写的源码,自定义view onMeasure方法的重写

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="自定义view onMeasure用法 (MeasureDemoActivity)"/>

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="@android:color/holo_red_light"/>

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

String widthSpec = MeasureSpec.toString(widthMeasureSpec);

String heightSpec = MeasureSpec.toString(heightMeasureSpec);

Log.d("measure_spec", widthSpec + " --- " + heightSpec);

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

Log.d("measure_spec", getMeasuredWidth() + " " + getMeasuredHeight());

}

02-21 19:07:23.740: D/measure_spec(19713): MeasureSpec: EXACTLY 720 MeasureSpec: AT_MOST 1143

02-21 19:07:23.740: D/measure_spec(19713): 720 1143

e46437760f928c02d7918045dbb75969.png

0818b9ca8b590ca3270a3433284dd417.png 如果自定义view的宽高设置为wrap_content 可以看到 measureSpec的值为了 AT_MOST (match_parent   对应的measureSpec为EXACTLY)

view是充满整个layout页面。很显然这并不是我们想要的效果

如果要实现设置wrap_content以后view的宽高刚好是view content的宽高,则需要重写onMeasure

(至于怎么重写,先不讨论、、可以参考 TextView的源码)

另外摘一段网上的代码

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int desiredWidth = 100;

int desiredHeight = 100;

int widthMode = MeasureSpec.getMode(widthMeasureSpec);

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

int heightMode = MeasureSpec.getMode(heightMeasureSpec);

int heightSize = MeasureSpec.getSize(heightMeasureSpec);

int width;

int height;

//Measure Width

if (widthMode == MeasureSpec.EXACTLY) {

//Must be this size

width = widthSize;

} else if (widthMode == MeasureSpec.AT_MOST) {

//Can't be bigger than...

width = Math.min(desiredWidth, widthSize);

} else {

//Be whatever you want

width = desiredWidth;

}

//Measure Height

if (heightMode == MeasureSpec.EXACTLY) {

//Must be this size

height = heightSize;

} else if (heightMode == MeasureSpec.AT_MOST) {

//Can't be bigger than...

height = Math.min(desiredHeight, heightSize);

} else {

//Be whatever you want

height = desiredHeight;

}

//MUST CALL THIS

setMeasuredDimension(width, height);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值