<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义view onMeasure用法 (MeasureDemoActivity)"/>
<phoebe.frame.view.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_red_light"/>
</LinearLayout>
@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
view是充满整个layout页面。很显然这并不是我们想要的效果
如果要实现设置wrap_content以后view的宽高刚好是view content的宽高,则需要重写onMeasure
(至于怎么重写,先不讨论、、可以参考 TextView的源码)
另外摘一段网上的代码
http://stackoverflow.com/questions/12266899/onmeasure-custom-view-explanation
@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);
}