目录
自定义ViewGroup
所有父控件(布局)都是 ViewGroup的子类,ViewGroup是一个抽象类,它里面有一个抽象方法 onLayout(),这个方法的作用就是摆放它所有的子控件(安排位置),因为是抽象类,在布局文件中可以使用View但是不能直接使用 ViewGroup。
- 自定义 View 需要重写:
- onMeaure():确定 View 的大小。
- onDraw() :绘制 View 的内容。
- 自定义 ViewGroup 需要重写:
- onMesure():测量子 view 的大小,才能确定 ViewGroup 的大小。
- onLayout() :确定子 View 的位置。
- onDraw():不是必须重写的,甚至不一定会被调用,只有当ViewGroup拥有 background 或 调用setWillNotDraw(false) 后才会回调 onDraw() 。
Measure测量方法
- measureChild():测量某一个child的宽高,不支持margin值。
- 调用 getChildMeasureSpec() 生成子视图的 MeasureSpec ,成功后通知子视图执行 measure()。
- measureChildWithMargins():测量某一个child的宽高,考虑margin值。
- 调用 getChildMeasureSpec() 生成子视图的 MeasureSpec ,成功后通知子视图执行 measure()。
- 注意:measureChildWithMargins和measureChild区别:measureChild父控件支不支持margin属性。
- measureChildren():遍历ViewGroup中所有的子控件。
- getChildCount():返回子View的数量。
- MeasureSpec.getSize/getMode(widthMeasureSpec/heightMeasureSpec):在 widthMeasureSpec 或 heightMeasureSpec 中,模式表示了父视图对子视图尺寸的约束方式。
- getChildMeasureSpec():根据父视图的 MeasureSpec 和 子视图的 LayoutParams 属性来生成 子视图的 MeasureSpec。
- Android 为 ViewGroup 提供子View测量模式默认方法:ViewGroup.getChildMeasureSpec()和 View.getDefaultSize()一样。
ViewGroup 类中默认提供了几个测量子 View 的方法,源码
//测量子视图
protected void measureChild(View child, int parentWidthMeasureSpec,int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
final int size = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < size; ++i) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
}
//测量子视图并计算其Margin
protected void measureChildWithMargins(View child,int parentWidthMeasureSpec, int widthUsed,int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin+ widthUsed, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin+ heightUsed, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
//获取子View的MeasureSpec,对于ViewGroup来说,这是非常重要的一个方法!!
int getChildMeasureSpec(int spec, int padding, int childDimension) { ... }
Measure测量
- 测量的时候父控件的onMeasure() 会遍历所有的子控件,挨个调用子控件的measure() ,measure() 会调用onMeasure。然后会调用setMeasureDimension() 保存测量的大小(得到子控件大小,确定ViewGroup大小),一次遍历下来,第一个子控件以及这个子控件中的所有子控件都会完成测量工作;然后开始测量第二个子控件…;最后父控件所有的子控件都完成测量以后会调用setMeasureDimension方法保存自己的测量大小。
- ViewGroup在执行Layout过程是使用遍历来调用子View的Layout方法,并制定其具体显示的位置,从而来决定其布局位置。
ViewGroup 为 childView 指定测量模式
ViewGroup会为childView指定测量模式,getChildMeasureSpec方法默认的测量模式,可查看源码。
- 父视图为 EXACTLY
- 子视图大小为 固定值、match_parent,子视图为 EXACTLY模式。
- 子视图大小为 WRAP_CONTENT,子视图为 AT_MOST 模式。
- 父视图为 AT_MOST
- 子视图大小为 固定值,子视图为 EXACTLY模式。
- 子视图大小为 MATCH_PARENT、WRAP_CONTENT,子视图为 AT_MOST模式。
- 父视图为 UNSPECIFIED
- 子视图大小为 固定值,子视图为 EXACTLY模式。
- 子视图大小为 MATCH_PARENT、WRAP_CONTENT,UNSPECIFIED
源代码:getChildMeasureSpec()
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
int size = Math.max(0, specSize - padding);
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on us
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size, but our size is not fixed.
// Constrain child to not be bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent asked to see how big we want to be
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
// Child wants a specific size... let them have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size... find out how big it should
// be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
//noinspection ResourceType
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
重写OnMeasure()
2种遍历测量所有子 View
- 第一种:调用 measureChildren(),一次性测量所有的子 View。遍历所有子 View,根据 measuredWidth 和 mesuredHeight 计算 ViewGroup 尺寸。
- 第二种:调用 measureChild 或 measureChildWithMargin(区别,ViewGroup 的 LayoutParams 是否允许 margin)来测量子 View,并在这个过程中计算 ViewGroup 的大小。
在计算完毕后,调用setMeasuredDimension(w, h)来设置最终的测量结果。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 因为onMeasure()可能会执行多次,所以需要清除
clearMeasureParams();//内存 抖动
// 先度量孩子
int childCount = getChildCount();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
// 获取父视图给定的宽高
int selfWidth = MeasureSpec.getSize(widthMeasureSpec);
int selfHeight = MeasureSpec.getSize(heightMeasureSpec);
List<View> lineViews = new ArrayList<>(); //保存一行中的所有的view
int lineWidthUsed = 0; // 记录这行已经使用了多宽的size
int lineHeight = 0; // 记录一行的行高
int parentNeededWidth = 0; // measure过程中,子View要求的父ViewGroup的宽
int parentNeededHeight = 0; // measure过程中,子View要求的父ViewGroup的高
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
LayoutParams childLP = childView.getLayoutParams();
// 判断子view是可见的
if (childView.getVisibility() != View.GONE) {
//将layoutParams转变成为 measureSpec
// 第一个参数:父视图给 的测量规范
// 第二个参数:内边距
// 第三个参数:子视图自身的布局参数值
int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight,childLP.width);
int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom,childLP.height);
// 测量子控件
childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
// 获取子view的度量宽高
int childMesauredWidth = childView.getMeasuredWidth();
int childMeasuredHeight = childView.getMeasuredHeight();
// 如果需要换行。子view宽度 + 一行已使用的宽度 + 横向的间距 > 父视图的宽高
if (childMesauredWidth + lineWidthUsed + mHorizontalSpacing > selfWidth) {
// 一旦换行,我们就可以判断当前行需要的宽和高了,所以此时要记录下来
allLines.add(lineViews);
lineHeights.add(lineHeight);
// 父类需要的宽,进行累加
parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
lineViews = new ArrayList<>();
lineWidthUsed = 0;
lineHeight = 0;
}
// view 是分行layout的,所以要记录每一行有哪些view,这样可以方便layout布局
lineViews.add(childView);
// 记录一行已使用的宽 = 一行已使用的宽 + 子类测量的宽 + 横向的间距
lineWidthUsed = lineWidthUsed + childMesauredWidth + mHorizontalSpacing;
lineHeight = Math.max(lineHeight, childMeasuredHeight);
//处理最后一行数据
if (i == childCount - 1) {
allLines.add(lineViews);
lineHeights.add(lineHeight);
parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
}
}
}
// 再度量自己,保存
// 根据子View的度量结果,来重新度量自己ViewGroup
// 作为一个ViewGroup,它自己也是一个View,它的大小也需要根据它的父亲给它提供的宽高来度量
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int realWidth = (widthMode == MeasureSpec.EXACTLY) ? selfWidth: parentNeededWidth;
int realHeight = (heightMode == MeasureSpec.EXACTLY) ?selfHeight: parentNeededHeight;
setMeasuredDimension(realWidth, realHeight);
}
ViewGroup中的 onLayout()
- ViewGroup中的onLayout() 是一个抽象方法,所有ViewGroup的子类都必须重写这个方法。
- LinearLayout、RelativeLayout等布局,都重写了这个方法,在内部按照各自的规则对子视图进行布局的。
@Override protected abstract void onLayout(boolean changed, int l, int t, int r, int b);
自定义一个布局,只要能够包含一个子视图,并且让子视图正常显示出来就可以了
FlowLayout Demo项目
示例图
public class FlowLayout extends ViewGroup {
// TODO 每个item横向和纵向的间距
private int mHorizontalSpacing = dp2px(16);
private int mVerticalSpacing = dp2px(8);
// 记录所有的行,一行一行的存储,用于layout
private List<List<View>> allLines = new ArrayList<>();
// 记录每一行的行高,用于layout
List<Integer> lineHeights = new ArrayList<>();
public FlowLayout(Context context) {
super(context);
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void clearMeasureParams() {
allLines.clear();
lineHeights.clear();
}
//度量
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 因为onMeasure()可能会执行多次,所以需要清除
clearMeasureParams();//内存 抖动
// 先度量孩子
int childCount = getChildCount();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
// 获取父视图给定的宽高
int selfWidth = MeasureSpec.getSize(widthMeasureSpec);
int selfHeight = MeasureSpec.getSize(heightMeasureSpec);
List<View> lineViews = new ArrayList<>(); //保存一行中的所有的view
int lineWidthUsed = 0; // 记录这行已经使用了多宽的size
int lineHeight = 0; // 记录一行的行高
int parentNeededWidth = 0; // measure过程中,子View要求的父ViewGroup的宽
int parentNeededHeight = 0; // measure过程中,子View要求的父ViewGroup的高
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
LayoutParams childLP = childView.getLayoutParams();
// 判断子view是可见的
if (childView.getVisibility() != View.GONE) {
//将layoutParams转变成为 measureSpec
// 第一个参数:父视图给 的测量规范
// 第二个参数:内边距
// 第三个参数:子视图自身的布局参数值
int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight,childLP.width);
int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom,childLP.height);
// 测量子控件
childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
// 获取子view的度量宽高
int childMesauredWidth = childView.getMeasuredWidth();
int childMeasuredHeight = childView.getMeasuredHeight();
// 如果需要换行。子view宽度 + 一行已使用的宽度 + 横向的间距 > 父视图的宽高
if (childMesauredWidth + lineWidthUsed + mHorizontalSpacing > selfWidth) {
// 一旦换行,我们就可以判断当前行需要的宽和高了,所以此时要记录下来
allLines.add(lineViews);
lineHeights.add(lineHeight);
// 父类需要的宽,进行累加
parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
lineViews = new ArrayList<>();
lineWidthUsed = 0;
lineHeight = 0;
}
// view 是分行layout的,所以要记录每一行有哪些view,这样可以方便layout布局
lineViews.add(childView);
// 记录一行已使用的宽 = 一行已使用的宽 + 子类测量的宽 + 横向的间距
lineWidthUsed = lineWidthUsed + childMesauredWidth + mHorizontalSpacing;
lineHeight = Math.max(lineHeight, childMeasuredHeight);
//处理最后一行数据
if (i == childCount - 1) {
allLines.add(lineViews);
lineHeights.add(lineHeight);
parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
}
}
}
// 再度量自己,保存
// 根据子View的度量结果,来重新度量自己ViewGroup
// 作为一个ViewGroup,它自己也是一个View,它的大小也需要根据它的父亲给它提供的宽高来度量
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int realWidth = (widthMode == MeasureSpec.EXACTLY) ? selfWidth: parentNeededWidth;
int realHeight = (heightMode == MeasureSpec.EXACTLY) ?selfHeight: parentNeededHeight;
setMeasuredDimension(realWidth, realHeight);
}
//布局
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int lineCount = allLines.size();
int curL = getPaddingLeft();
int curT = getPaddingTop();
// 遍历每一行,布局其中的子视图
for (int i = 0; i < lineCount; i++){
// 获取每一行的view
List<View> lineViews = allLines.get(i);
// 获取每一行的高
int lineHeight = lineHeights.get(i);
for (int j = 0; j < lineViews.size(); j++){
View view = lineViews.get(j);
// 计算视图的位置
int left = curL;
int top = curT;
// 这种方式是获取不到宽高的,只有调用child.layout之后才能获取宽和高
// int right = left + view.getWidth();
// int bottom = top + view.getHeight();
int right = left + view.getMeasuredWidth();
int bottom = top + view.getMeasuredHeight();
// 布局子视图
view.layout(left,top,right,bottom);
curL = right + mHorizontalSpacing;// 更新当前行的左坐标
}
// 更新顶部坐标和重置左坐标,用于下一行
curT = curT + lineHeight + mVerticalSpacing;
curL = getPaddingLeft();
}
}
public static int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().getDisplayMetrics());
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.dfg.flowlayout.FlowLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mFlowLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="儿时凿壁偷了谁家的光" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="亲爱的" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="我是不是看上去真的很胖" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="这个问题实在不好回答" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="公交车上,有一美女" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="和一个外国人用英语交谈" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="交谈声很大" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="美女聊得很开学" />
</com.dfg.flowlayout.FlowLayout>
</ScrollView>