Android学习笔记-自定义View之View的测量
MeasureSpec
Android系统提供的我们来测量View的类
测量的模式
- EXACTLY : 精确值模式,当控件的layout_width 或者 layout_height 属性指定为具体的值,比如:android:layout_width=:“20dp” 或者为 match_parent,系统使用的就是这个模式
- AT_MOST :最大值模式,当控件的layout_width 或者 layout_height 指定为 wrap_content,控件的大小随着控件的子控件或控件的内容的变化而变化,控件的大小不超过父控件的最大尺寸;
- UNSPEIFIED : 不指定控件大小的测量模式,view想多大就多大 , 一般情况下自定义view时用;
View的测量实例
Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
}
/**
* 测量高
* @param heightMeasureSpec
* @return
*/
private int measureHeight(int heightMeasureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(heightMeasureSpec);
int specSize = MeasureSpec.getSize(heightMeasureSpec);
if(specMode == MeasureSpec.EXACTLY) {
//精确值模式
result = specSize;
}else if(specMode == MeasureSpec.AT_MOST) {
//最大值模式
result = 100;
result = Math.min(result,specSize);
}
return result;
}
/**
* 测量高
* @param widthMeasureSpec
* @return
*/
private int measureWidth(int widthMeasureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
if(specMode == MeasureSpec.EXACTLY) {
//精确值模式
result = specSize;
}else if(specMode == MeasureSpec.AT_MOST) {
//最大值模式
result = 200;
result = Math.min(result,specSize);
}
return result;
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wang.myview.MainActivity">
<com.wang.myview.view.MeasureView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
/>
</FrameLayout>
运行结果:
稍后配图。。。