Android自定义View2--onMeasure,onLayout源码分析和自定义流式布局
onMeasure() 测量View的大小
onLayout() 确定子布局
onDraw() 实际绘制内容
自定义View主要是实现onMeasure+onDraw
自定义ViewGroup主要是实现onMeasure+onLayout
一、onMeasure源码分析
onMeasure的时候是先量子View,再计算和保存自己的尺寸,以FrameLayout的源码为例:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
**//1、测量子View**
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
**//2、计算子View的最大宽高**
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
**//3、测量自己,确定自己的宽高**
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
count = mMatchParentChildren.size();
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
final int width = Math.max(0, getMeasuredWidth()
- getPaddingLeftWithForeground() - getPaddingRightWithForeground()
- lp.leftMargin - lp.rightMargin);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
lp.leftMargin + lp.rightMargin,
lp.width);
}
final int childHeightMeasureSpec;
if (lp.height == LayoutParams.MATCH_PARENT) {
final int height = Math.max(0, getMeasuredHeight()
- getPaddingTopWithForeground() - getPaddingBottomWithForeground()
- lp.topMargin - lp.bottomMargin);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
height, MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
lp.topMargin + lp.bottomMargin,
lp.height);
}
**//4、当子View是MATCH_PARENT属性,再将子View设置成测量出来的parent的宽高,也就实现了View的MATCH_PARENT**
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
可以看到这四步总结onMeasure:首先,它会遍历所有子View,并记录下子View的最大宽高,最大宽高加上padding margin作为FrameLayout自身的尺寸。然后,如果FrameLayout是不确定大小的模式,子View又是MATCH_PARENT属性的,就需要为这些子View重新度量。
二、onLayout源码分析
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}
void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
final int count = getChildCount();
final int parentLeft = getPaddingLeftWithForeground();
final int parentRight = right - left - getPaddingRightWithForeground();
final int parentTop = getPaddingTopWithForeground();
final int parentBottom = bottom - top - getPaddingBottomWithForeground();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = DEFAULT_CHILD_GRAVITY;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin;
break;
}
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = parentTop + lp.topMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
onLayout:FrameLayout对每个子View的layout过程是相同的,它会遍历所有的子View,通过子View的gravity属性进行xy轴偏移量的计算,最后调用child.layout()对子View进行布局。
小知识:
getMeasuredWidth:
1、在measure()过程结束后就可以获取对应的值。
2、通过setMeasuredDimension()方法来进行设置的。
getWidth:
1、在layout()过程结束后才能获取到;
2、通过视图右边的坐标减去左边的坐标计算出来的。
三、 自定义流式布局的代码:
FlowLayout.java:
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.lz.langyabi.util.utilcode.ConvertUtils;
import java.util.ArrayList;
import java.util.List;
public class FlowLayout extends ViewGroup {
private static final String TAG = "FlowLayout";
private int mHorizontalSpacing = ConvertUtils.dp2px(16);
private int mVertialSpacing = ConvertUtils.dp2px(8);
private List<List<View>> allLines = new ArrayList<>();//记录所有的行,一行一行的存储,用于layout
List<Integer> lineHeights = new ArrayList<>();//记录每一行的行高,用于layout
public FlowLayout(Context context) {
super(context);
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
//主题style
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
private void initMeasuredParams() {
allLines = new ArrayList<>();
lineHeights = new ArrayList<>();
}
//度量,测量View的大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//initMeasuredParams不可以放到构造函数里面,放到这里可以是因为构造函数的生命周期中只调用一次,但onMeasure可能会多次触发
initMeasuredParams();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
List<View> lineViews = new ArrayList<>();//保存一行中的所有view
int lineWidthUsed = 0; //记录这行已经使用了多宽的size
int lineHeight = 0; // 一行的高
int selfWidth = MeasureSpec.getSize(widthMeasureSpec);//ViewGroup解析的父亲给我的宽度
int selfHeight = MeasureSpec.getSize(heightMeasureSpec);//ViewGroup解析的父亲给我的高度
int parentNeedWidth = 0;//measure过程中,子View要求的父ViewGroup的宽
int parentNeedHeight = 0;//measure过程中,子View要求的父ViewGroup的高
//度量子View
for (int i = 0; i < getChildCount(); i++) {
View childView = getChildAt(i);
LayoutParams childLP = childView.getLayoutParams();
//将layoutParams转变成measureSpec
int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight, childLP.width);
int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom, childLP.height);
childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
//获取子View的度量宽高
int childMeasuredWidth = childView.getMeasuredWidth();
int childMeasuredHeight = childView.getMeasuredHeight();
//当新一个要加入的item的宽度加上现在累积的width的宽度大于行宽
if (childMeasuredWidth + lineWidthUsed > selfWidth) {
//所有行的数据和所有行的行高记录下来,用于layout
allLines.add(lineViews);
lineHeights.add(lineHeight);
//一旦换行,我们就可以判断当前行需要的宽和高了,所以要记录下来
parentNeedHeight = parentNeedHeight + lineHeight + mVertialSpacing;
//宽度要记录,因为很多时候并不是布满全局
parentNeedWidth = Math.max(parentNeedWidth, lineWidthUsed + mHorizontalSpacing);
lineViews = new ArrayList<>();
lineWidthUsed = 0;
lineHeight = 0;
}
//View是分行layout的,所以要记录每一行有哪些View,这样可以方便layout布局
lineViews.add(childView);
//每行都有自己的宽高
lineWidthUsed = lineWidthUsed + childMeasuredWidth + mHorizontalSpacing;
lineHeight = Math.max(lineHeight, childMeasuredHeight);
}
//度量自己
//根据子View的度量结果,来重新度量自己的ViewGroup
//作为一个ViewGroup,它自己也是一个View,它的大小也需要根据它的父亲给他提供的宽高来度量
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//明确了大小就是父亲(ViewGroup)给的
int realWidth = (widthMode == MeasureSpec.EXACTLY) ? selfWidth : parentNeedWidth;
int realHeight = (heightMode == MeasureSpec.EXACTLY) ? selfHeight : parentNeedHeight;
setMeasuredDimension(realWidth, realHeight);
}
//布局,确定子View布局
@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 lineHight = lineHeights.get(i);
for (int j = 0; j < lineViews.size(); j++) {
View view = lineViews.get(j);
int left = curL;
int top = curT;
int right = left + view.getMeasuredWidth();
int bottom = top + view.getMeasuredHeight();
view.layout(left, top, right, bottom);
curL = right + mHorizontalSpacing;
}
curT = curT + mVertialSpacing + lineHight;
curL = getPaddingLeft();
}
}
//实际绘制内容
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
设置数据的代码,我这里没用adpter去管理,主要是梳理自定义View:
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.nex3z.flowlayout.FlowLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillAutoSpacingLayout();
}
private void fillAutoSpacingLayout() {
FlowLayout flowLayout = findViewById(R.id.flow);
//R.array.lorem_ipsum是values文件夹下的本地数据
String[] dummyTexts = getResources().getStringArray(R.array.lorem_ipsum);
for (String text : dummyTexts) {
TextView textView = buildLabel(text);
flowLayout.addView(textView);
}
}
private TextView buildLabel(String text) {
TextView textView = new TextView(this);
textView.setText(text);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setPadding((int)dpToPx(16), (int)dpToPx(8), (int)dpToPx(16), (int)dpToPx(8));
textView.setBackgroundResource(R.drawable.label_bg);
return textView;
}
private float dpToPx(float dp){
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
}
四、拓展
1、自定义布局的时候,遇到Error inflating class错误,先看看是否重写了至少两个构造方法。
2、通过adapter管理ViewGroup:
https://www.cnblogs.com/best-hym/p/12683944.html
3、自定义View基础:https://github.com/GcsSloop/AndroidNote
4、点赞头像层叠:https://github.com/LineChen/PileLayout
本文地址:https://blog.csdn.net/u013750244/article/details/107927552
上一篇: 清朝为何要将自己努力送出去培养的留美幼童全部关起来呢?
下一篇: 红芽芋头和白芽芋头的区别