Android系统中,View的绘制机制,主要是三个步骤,measure,layout,draw。而无论是View的派生类还是我们自定义View时,针对每个步骤处理各自的逻辑时,相应的需要重写onMeasure,onLayout,onDraw方法
Measure过程
这个过程中比较重要的是MeasureSpec。它是一个int型的变量,由mode和size两部分组成。其32位字节中,高2位是mode,后面是size。官方文档对它的说明是“封装了父容器对子视图的布局要求(A MeasureSpec encapsulates the layout requirements passed from parent to child.)”。也可以这样理解,View的MeasureSpec是由父容器的MeasureSpec和它自己的LayoutParams共同作用决定。
MeasureSpec.mode有三个可选值
- MeasureSpec.UNSPECIFIED——指父容器对子View的尺寸(宽高)没有任何限制,子View的宽高有LayoutParams决定
- MeasureSpec.AT_MOST——指父容器限制了子View尺寸允许范围的最大值,子View的宽高不能超过这个尺寸。
- MeasureSpec.EXACTLY——指父容器给子View的尺寸限制了固定的大小,子View应该服从这个边界。
关于父容器MeasureSpec对子View尺寸的影响,分两种情况:
- 当子View的宽高为具体的数值时,父容器的MeasureSpec对子View的specSize没有影响,只对specMode有影响。
- 当子View的宽高为wrap_content或match_parent时,父容器的MeasureSpec对子View的specMode和specSize都有影响。
具体可以参见系统源码
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 him 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);
}
View的measure过程中,实际的测量工作是在onMeasure方法中进行。虽然View基类的onMeasure方法实现非常简单。但通过阅读源码还是可以发现值得注意的地方。
* The actual measurement work of a view is performed in
* {@link #onMeasure(int, int)}, called by this method. Therefore, only
* {@link #onMeasure(int, int)} can and must be overridden by subclasses.
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
...
}
* <strong>CONTRACT:</strong> When overriding this method, you
* <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
* measured width and height of this view. Failure to do so will trigger an
* IllegalStateException, thrown by
* {@link #measure(int, int)}. Calling the superclass'
* {@link #onMeasure(int, int)} is a valid use.
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
//获取的是android:minWidth属性的值或者View背景图片的大小值
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
其中需要注意的就是当我们重写onMeasure方法时,必须要调用setMeasuredDimension方法来保存view的measuredWidth和measuredHeight。否则就抛出异常。
setMeasuredDimension方法,可以简单地理解为mMeasuredWidth和mMeasuredHeight。只是如果对象是ViewGroup,会多一个判断。执行到这个方法,就意味着一个View的measure过程结束。我也可以在调用setMeasuredDimension方法时,简单粗暴的传入一个特殊值,比如setMeasuredDimension(200,200)。
参见上面的源码,View默认的测量逻辑就是这样,如果measureSpec.mode为UNSPECIFIED,那么最终的mMeasuredWidth就是建议的最小值(LayoutParams中设置的minWIdth或者背景图片的最小宽度),否则就是measureSpec中的size。mMeasuredHeight的处理逻辑也是一样。
而像TextView,ImageView,Button等View的子类,他们的重写了onMeasure方法。所以最终的measuredWidth和measuredHeight可能就不是按View基类的实现逻辑处理的。比如TextView和ImageView,不会直接拿measureSpec的size当做最终的measuredWidth和measuredHeight,而是会去先测量其包含的字符或图片的高度,然后拿到View本身content这个高度(字符高度等),如果MeasureSpec是AT_MOST,而且View本身content的高度不超出MeasureSpec的size,那么可以直接用View本身content的高度(字符高度等),而不是像View直接用MeasureSpec的size做为View的measuredWidth和measuredHeight。
DecorView的measure过程
我们可以DecorView的measure过程来看看一个ViewGroup的measure过程。先看图
image.png
这里先讲讲DecorView的结构。DecorView本身是一个FrameLayout,他由两个子View组成:id为statusBarBackground的View和一个LinearLayout。对于statusBarBackground,我的理解是他表示手机屏幕最上方显示一些WIFI、手机型号之类的statusBar。而这个LinearLayout又由两部分组成:一个id为title的viewStup,用来惰性加载titleBar或者ActionBar;一个id为android.R.id.content的FrameLayout,它是我们通过setContentView为Activity设置布局的父容器。
从DecorView开始,一个Activity页面绘制的measure过程大致如下:
每一个Activity实例都包含一个PhoneWindow对象(mWindow),他会在attah方法中创建
mWindow = new PhoneWindow(this, window, activityConfigCallback);
关于这个PhoneWindow对象简单介绍下,它可以看做是一个Activity实例与View系统交互的桥梁。每一个Window(PhoneWindow的父类)对象都对应着一个View对象和一个ViewRootImpl对象。Window和View通过ViewRootImpl建立联系。具体到Activity实例来说,ViewRootImpl是它连接WindowManager和DecorView的纽带。
Activity页面的绘制过程是从ViewRootImpl的performTraversals方法开始的。
private void performTraversals() {
......
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
......
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
......
mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight());
......
mView.draw(canvas);
......
}
/**
* Figures out the measure spec for the root view in a window based on it's
* layout params.
*
* @param windowSize
* The available width or height of the window
*
* @param rootDimension
* The layout params for one dimension (width or height) of the
* window.
*
* @return The measure spec to use to measure the root view.
*/
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
// Window can't resize. Force root view to be windowSize.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
// Window wants to be an exact size. Force root view to be that size.
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
performTraversals方法中mView就是DecorView。Activity页面的绘制从DecorView开始。在调用mView.measure()方法之前,通过getRootMeasureSpec获取到两个MeasureSpec作为参数,getRootMeasureSpec方法的mWidth和mHeight参数是屏幕的宽和高,lp是WindowManager.LayoutParams。lp.width和lp.height的默认值都是MATCH_PARENT。所以通过getRootMeasureSpec生成的MeasureSpec的mode是EXACTLY,size是屏幕的宽和高。
因为DecorView本身是一个FrameLayout,所以接下来的Measure过程就会执行FrameLayout的measure方法。measure的两个参数就是getRootMeasureSpec生成的MeasureSpec。
在DecorView(也就是FrameLayout)的onMeasure方法,DecorView开始for循环测量自己的子View,测量完所有的子View再来测量自己。
//FrameLayout 的测量
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
....
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) {
// 遍历自己的子View,只要不是GONE的都会参与测量
// 基本思想就是父View把自己的MeasureSpec
// 传给子View结合子View自己的LayoutParams 算出子View 的MeasureSpec,然后继续往下传,
// 传递叶子节点,叶子节点没有子View,只要负责测量自己就好了。
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
....
....
}
}
....
//遍历完所有的子View的测量,再完成自身的Measure过程
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,childState << MEASURED_HEIGHT_STATE_SHIFT));
....
}
//ViewGroup类的measureChildWithMargins方法
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);
}
DecorView绘制的Measure过程大致就是这样,其中以FrameLayout的onMeasure方法为例,介绍了ViewGroup的onMeasure方法的大致处理逻辑。
Layout过程
View的绘制,执行完measure过程后,接下来是layout过程。来说拿DecorView来举例,
在performTraversals方法中,执行完mView.measure()方法,然后就是mView.layout()方法,也就是ViewGroup的layout方法。代码如下
public final void layout(int l, int t, int r, int b) {
if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) {
if (mTransition != null) {
mTransition.layoutChange(this);
}
super.layout(l, t, r, b);
} else {
// record the fact that we noop'd it; request layout when transition finishes
mLayoutCalledWhileSuppressed = true;
}
}
上段代码中的super.layout()方法,就是View的layout方法。而在View的layout方法中,会调用onLayout()方法,View类的onLayout()方法是个空方法
* <p>Derived classes should not override this method.
* Derived classes with children should override
* onLayout. In that method, they should
* call layout on each of their children.</p>
public void layout(int l, int t, int r, int b) {
....
// 设置View位于父视图的坐标轴,1、setFrame(l, t, r, b) 可以理解为给mLeft 、mTop、mRight、mBottom赋值,
// 然后基本就能确定View自己
// 在父视图的位置了,这几个值构成的矩形区域就是该View显示的位置,这里的具体位置都是相对与父视图的位置。
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
//判断View的位置是否发生过变化,看有必要进行重新layout吗
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
onLayout(changed, l, t, r, b);
if (shouldDrawRoundScrollbar()) {
if(mRoundScrollbarRenderer == null) {
mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
}
} else {
mRoundScrollbarRenderer = null;
}
mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
}
....
}
从源码的注释可以看出,View的子类需要重写onLayout方法,具体到各种类型的View和ViewGroup,实际也是在onLayout中处理布局逻辑。ViewGroup类的onLayout方法是个抽象方法,也就是说,继承ViewGroup的子类,必须实现onLayout方法,用来处理子View在容器中位置安排的逻辑。
在View.layout方法中,会调用到setFrame(l,t,r,b)方法,它是一个View用来确定其在父容器中上下左右(l,t,r,b)四个边界的位置,从而确定一个View在父容器中最终的位置和尺寸,(l,t,r,b)这四个值的计算,是通过measure过程中得到的MeasuredWidth和MeasuredHeight,以及LayoutParams中的一些layout_开头的参数共同起作用决定的。
默认情况下,MeasuredWidth和MeasuredHeight这两个值在得出layout(l,t,r,b)的四个参数时,起到很大作用,但是在自定义View时,它们不是必须的。也就是说调用layout方法时,我们可以指定任意left,top,right,bottom的值作为参数。这样我们也就可以理解为什么很多情况下一个控件的getWidth方法和getMeasuredWidth方法的返回值不同。前者返回的是right-left的值;后者返回的是MeasuredWidth。
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
public final int getWidth() {
return mRight - mLeft;
}
draw过程
View的draw过程一般有6个步骤
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
// Step 1, draw the background, if needed
int saveCount;
if (!dirtyOpaque) {
drawBackground(canvas);
}
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
drawAutofilledHighlight(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// Step 7, draw the default focus highlight
drawDefaultFocusHighlight(canvas);
if (debugDraw()) {
debugDrawFocus(canvas);
}
// we're done...
return;
}
......
......
}
从代码中可以看出onDraw方法是在dispatchDraw方法之前调用。其实从逻辑可以这样理解,在画布绘制是一层一层画的,背景是最下面的一层,而父容器是在子View的下面,所以是背景最先画出来,然后是父容器自己,然后才是子View,最后是描边。流程图如下。
nDraw方法是在第三步调用。onDraw(canvas) 方法是view用来draw 自己的,具体如何绘制,颜色线条什么样式就需要子View自己去实现,View的onDraw(canvas) 是空实现,ViewGroup 也没有实现,每个View的内容是各不相同的,所以需要由子类去实现具体逻辑。
至此,View绘制的measure、layout、draw过程大致就是这样了。
自定义布局属性
我们在自定义View时,除了根据需要重写onMeasure、onLayout、onDraw方法之外,有时候我们还需要用到自定义布局属性。其具体的实现方式是:
- 首先,在res/values/styles.xml文件中,声明我们需要的自定义属性
<declare-styleable name="CustomTestView">
<attr name="default_size" format="dimension"></attr>
<declare-styleable>
其中的declare-styleable为属性集合的标签,用于给属性分组。
- 然后在布局文件中,就可以用到这个属性了,有一个地方需要注意的是,需要在根标签上声明命名空间,如此处的"zlj"。 命名空间后面取得值是固定的:"http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:zlj="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".ui.activity.SecondActivity"
tools:showIn="@layout/activity_second">
<com.zacky.widget.CustomTestView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
zlj:default_size="100dp"
/>
</android.support.constraint.ConstraintLayout>
- 最后在我们的自定义View里面,获取到layout文件中设置的这个属性值
public class CustomTestView extends View {
int defaultSize;
public CustomTestView(Context context) {
super(context);
}
public CustomTestView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTestView);
defaultSize = typedArray.getDimensionPixelSize(R.styleable.CustomTestView_default_size,100);
typedArray.recycle();
}
}
我们可以通过构造函数中的AttributeSet,获取到自定义属性。最后记得将TypedArray对象回收。
本文参考:
https://www.jianshu.com/p/5a71014e7b1b
https://blog.csdn.net/a553181867/article/details/51583060
网友评论