onMeasure() 测量的方法
android 系统为我们提供了一个类
MeasureSpec 它可以用来测量view
测量模式 EXACTLy 精确值模式 系统默认使用
AT_MOST 最大值模式
VIew类默认的onMeasure方法只支持EXACTLY模式,所以如果在自定义控件的时候不重写onMeaure方法的话,
就只能使用EXACTLY模式,控件可以响应你指定的具体宽度或者式match_parent属性
而如果要让自定义的View支持wrap_content属性,就必须重写onMeasure 方法类指定wrap_content的大小
一 新建一个类继承制View
重写构造方法
重写onMeasure 方法
package com.yifei.myapplication;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class MyView extends View {
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
}
private int measureHeight(int heightMeasureSpec) {
int result=0;
int heightMode = MeasureSpec.getMode(heightMeasureSpec);//得到测量模式
int heightSize = MeasureSpec.getSize(heightMeasureSpec); //得到测量大小
//判断属于哪一种模式
if(heightMode==MeasureSpec.EXACTLY){//是否式精确值模式
Log.d("MyView", "heightMode: "+"EXACTLY");
result =heightSize;
}else if(heightMode==MeasureSpec.AT_MOST){ //是否是最大值模式
Log.d("MyView", "heightMode: "+"AT_MOST");
result = 55;
result=Math.min(result,heightSize);
}
return result;
}
private int measureWidth(int widthMeasureSpec) {
int result =0;
int widthMode = MeasureSpec.getMode(widthMeasureSpec); //得到测量的模式
int widthSize = MeasureSpec.getSize(widthMeasureSpec); //得到测量的大小
if(widthMode==MeasureSpec.EXACTLY){
Log.d("MyView", "measureWidth: "+"EXACTLY");
result = widthSize;
}else if(widthMode==MeasureSpec.AT_MOST){
Log.d("MyView", "measureWidth: "+"AT_MOST");
result = 100;
result = Math.min(result,widthSize);
}
return result;
}
}
xml布局的调用当为wrap_content时的模式式最大值模式
<com.yifei.myapplication.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff0000"
/>
xml布局调用为match_parent时的模式为精确者模式
<com.yifei.myapplication.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"
android:layout_marginTop="40dp"
/>
设置一个固定的值时为 精确者模式
<com.yifei.myapplication.MyView
android:layout_width="200dp"
android:layout_height="202dp"
android:background="#ff0000"
android:layout_marginTop="40dp"
/>