setWillNotDraw(false);
自定义View中如果重写了onDraw()即自定义了绘制,那么就应该在构造函数中调用view的setWillNotDraw(false),设置该flag标志。其实默认该标志就是false。这样可以走自定义view的ondrawa方法
onMeasure方法中,
// 获得它的父容器为它设置的测量模式和大小
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);//父view能提供给
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
继承View,实现自己想要的组件,那么需要使用到setMeasuredDimension这个方法,这个方法决定了当前View的大小,可以在onMeasure方法中调用;
makeMeasureSpec方法来提供子view测量用的的spec
MeasureSpec.makeMeasureSpec(size, mode);
自定义view,继承viewgroup,重写onmeasure方法,测量view的大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获得它的父容器为它设置的测量模式和大小
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int resultWidth = 0;
int resultHeight = 0;
for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
View childAt = getChildAt(i);
// viewgroup中的方法,测量子view的大小,需要传入父容器的widthMeasureSpec等
measureChild(childAt, widthMeasureSpec, heightMeasureSpec);
// 获取子view的宽高
int childWidth = childAt.getMeasuredWidth();
int childHeight = childAt.getMeasuredHeight();
resultHeight = Math.max(resultHeight, childHeight);
if (childWidth + resultWidth > sizeWidth) {
break;
}
resultWidth = resultWidth + childWidth ;
}
// 测量viewgroup中的所有的子view的宽高后,获取到这个自定义view的大小,设置此view的大小
setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : resultWidth, resultHeight);
}
MeasurSpec的详细解析:https://blog.csdn.net/chunqiuwei/article/details/44515345
网友评论