参考:安卓群英会
1.一个控件最终的大小取决于,父容器,布局文件的申请参数,,该控件自身的大小.
2.MeasureSpec 类 . 32 位的int值,前2位表示测量模式,后面30位表示数值的大小.
对于测量模式来说有三种:默认的也是具体的.
1.EXACTLY(精准的)
当您设置View的layout_height属性或layout_width属性为具体的值或者为match_parent(填充父容器)时候,系统就将View测量模式设置为EXACTLY模式。
2.AT_MOST(最大值)
即布局为最大值模式,那么什么时候系统会将View调整为AT_MOST模式了,即当您设置View的layout_height属性或layout_width属性为wrap_content(包裹内容)时候。
3.UNSPECIFIED(未确定)
即没有确定,没有指定大小测量模式,view即“心有多大,舞台就有多大"。这个方法,一般在自定义控件中才能用到。
3.如果在自定义控件当中,如果没有重写onMeasure方法,默认采用的是EXACTLY(精准的)模.此时,如果布局中的控件宽高模式是wrapContent,则实际上填充整个父窗体,如果是具体的值,则就表示具体值.
代码实例:
主页面的布局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.viewdemo2.MainActivity">
<com.example.administrator.viewdemo2.MyView
android:background="#008000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></com.example.administrator.viewdemo2.MyView>
</RelativeLayout>
自定义控件:
public class MyView extends View {
private static final String TAG = "MyView";
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
实际的效果,如果布局中是wrap_content.而且没有重写measure方法.实际上match_parent
如果修改布局长宽为具体值,效果也会是具体值.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.viewdemo2.MainActivity">
<com.example.administrator.viewdemo2.MyView
android:background="#008000"
android:layout_width="40dp"
android:layout_height="40dp"
></com.example.administrator.viewdemo2.MyView>
</RelativeLayout>
如果当布局中wrap_content时.重新onMeasure方法.
public class MyView extends View {
private static final String TAG = "MyView";
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureLength(widthMeasureSpec),
measureLength(heightMeasureSpec));
}
private int measureLength(int measureSpec) {
int result=0;
//得到测量模式和长度
int mode = MeasureSpec.getMode(measureSpec);
int length = MeasureSpec.getSize(measureSpec);
//如果测量模式是exactly,直接用父容器测量的
if (mode==MeasureSpec.EXACTLY){
result=length;
}else{
//如果测量模式是AT_MOST,自己指定一个值,并且与父容器得到的值比较,用最少的值.
result=100;
if (mode==MeasureSpec.AT_MOST){
result=Math.min(result,length);
}
//如果测量模式是unspet.可以用自己指定的值.
}
return result;
}
}
<com.example.administrator.viewdemo2.MyView
android:background="#008000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></com.example.administrator.viewdemo2.MyView>
</RelativeLayout>
效果图如下