在我们自己定义控件的时候可能你会用到onMeasure方法,以下就具体的给大家介绍一下这种方法:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
我们自己定义一个类继承View或者ViewGroup之后重写onMeasure方法,我们看到这种方法传递进来两个变量,这里做一下解释:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 宽和高的计算模式 int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
//真正的宽和高的数值 int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeigth = MeasureSpec.getSize(heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(sizeWidth, sizeHeigth); }
ViewGroup.LayoutParams.MATCH_PARENT
假如你用了wrap_content,那么这里推荐你的宽和高还是320*480
ViewGroup.LayoutParams.WRAP_CONTENT
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 宽和高的计算模式 int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); //拿到父容器推荐的宽和高 int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeigth = MeasureSpec.getSize(heightMeasureSpec);
<span style="white-space:pre"> </span>//这里測量每个孩子的宽和高 if (modeWidth == MeasureSpec.ATMOST) //sizeWidth = 计算的值 } if (modeHeight == MeasureSpec.ATMOST<span style="font-family: Arial, Helvetica, sans-serif;">)</span> //sizeHeigth = 计算的值 } setMeasuredDimension(sizeWidth, sizeHeigth); }
好了今天如此具体的解说了这种方法的作用及其參数的作用,大家自己也去试试吧