寫在前面的幾句話
<p>
上一篇文章對(duì)于LinearLayout的屬性有了較為詳細(xì)介紹抛杨,那么對(duì)于LinearLayout的源碼其實(shí)也是很有必要去了解一下的,畢竟在開發(fā)工作中鄙币,自定義View與ViewGroup其實(shí)是蠻常見的工作之一肃叶,所以對(duì)LinearLayout源碼進(jìn)行解讀相信對(duì)于以后的開發(fā)工作是很有幫助的
對(duì)于一個(gè)View(ViewGroup)來(lái)說實(shí)現(xiàn)無(wú)非于三個(gè)流程,onMeasure(測(cè)量)十嘿,onLayout(定位)因惭,onDraw(繪制),接下來(lái)就對(duì)這三個(gè)部分一一分析
但是首先還是對(duì)LinearLayout變量進(jìn)行介紹
1.LinearLayout變量
<p>
其實(shí)LinearLayout變量與上篇屬性篇中關(guān)聯(lián)比較大,這里就直接上代碼和注釋了
//基準(zhǔn)線對(duì)齊變量绩衷,默認(rèn)為true
private boolean mBaselineAligned = true;
//基準(zhǔn)線對(duì)齊的對(duì)象index
private int mBaselineAlignedChildIndex = -1;
//baseline額外的偏移量
private int mBaselineChildTop = 0;
//linearlayout的排列方式
private int mOrientation;
//linearlayout的對(duì)齊方式
private int mGravity = Gravity.START | Gravity.TOP;
//測(cè)量的時(shí)候通過累加得到所有子控件的高度和(Vertical)或者寬度和(Horizontal) ;
private int mTotalLength;
//權(quán)重總和變量
private float mWeightSum;
//權(quán)重最小尺寸的對(duì)象
private boolean mUseLargestChild;
//基準(zhǔn)線對(duì)其相關(guān)
private int[] mMaxAscent;
private int[] mMaxDescent;
//分隔條相關(guān)
private Drawable mDivider;
private int mDividerWidth;
private int mDividerHeight;
private int mShowDividers;
private int mDividerPadding;
2.measure流程
<p>
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
當(dāng)我們?cè)O(shè)置不同的orientation就會(huì)進(jìn)入不同的測(cè)量流程蹦魔,我們以其中的一個(gè)測(cè)量流程為例子進(jìn)行說明,那么另外的測(cè)量流程也就不難理解了
我們以measureVertical為例來(lái)分析
由于代碼相對(duì)比較長(zhǎng)唇聘,所以根據(jù)不同的功能分段分析
(1).變量
<p>
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//mTotalLength為 LinearLayout的成員變量版姑,在這里指的是所有子控件的高度和
mTotalLength = 0;
//所有子控件中寬度最大的值
int maxWidth = 0;
//子控件的測(cè)量狀態(tài)
int childState = 0;
//子控件中l(wèi)ayout_weight<=0的View最大高度
int alternativeMaxWidth = 0;
//子控件中l(wèi)ayout_weight>0的View最大高度
int weightedMaxWidth = 0;
//子控件是否全是match_parent
boolean allFillParent = true;
//子控件所有l(wèi)ayout_weight的和
float totalWeight = 0;
//獲取子控件數(shù)量
final int count = getVirtualChildCount();
//獲取測(cè)量模式
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//當(dāng)子控件為match_parent的時(shí)候,該值為ture
boolean matchWidth = false;
boolean skippedMeasure = false;
//基準(zhǔn)線對(duì)齊的對(duì)象index
final int baselineChildIndex = mBaselineAlignedChildIndex;
//權(quán)重最小尺寸的對(duì)象
final boolean useLargestChild = mUseLargestChild;
//子View中最高高度
int largestChildHeight = Integer.MIN_VALUE;
}
(2).測(cè)量Part1
<p>
其實(shí)這段代碼前面自帶的注釋就很好說明接下來(lái)這一段代碼做的事情了迟郎,
See how tall everyone is. Also remember max width.
就不對(duì)這句話進(jìn)行翻譯了剥险,接下來(lái)看這一段代碼做了什么事情
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//...接上面的變量
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
//這個(gè)不解釋了,measureNullChild獲得的結(jié)果是0
if (child == null) {
mTotalLength += measureNullChild(i);
continue;
}
//這個(gè)也不解釋了
if (child.getVisibility() == View.GONE) {
i += getChildrenSkipCount(child, i);
continue;
}
// 根據(jù)showDivider的值(before/middle/end)來(lái)決定遍歷到當(dāng)前子控件時(shí)宪肖,高度是否需要加上divider的高度
// 比如showDivider為before表制,那么只會(huì)在第0個(gè)子控件測(cè)量時(shí)加上divider高度,其余情況下都不加
//這里測(cè)量不包括end的情況
if (hasDividerBeforeChildAt(i)) {
mTotalLength += mDividerHeight;
}
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
//根據(jù)子控件的權(quán)重得到總權(quán)重
totalWeight += lp.weight;
// 測(cè)量模式有三種:
// * UNSPECIFIED:父控件對(duì)子控件無(wú)約束
// * Exactly:父控件對(duì)子控件強(qiáng)約束控乾,子控件永遠(yuǎn)在父控件邊界內(nèi)么介,越界則裁剪。如果要記憶的話蜕衡,可以記憶為有對(duì)應(yīng)的具體數(shù)值或者是Match_parent
// * AT_Most:子控件為wrap_content的時(shí)候壤短,測(cè)量值為AT_MOST。
if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
//父控件高度為match_parent且子控件高度為0,weight>0情況下
// 測(cè)量到這里的時(shí)候久脯,會(huì)給個(gè)標(biāo)志位纳胧,稍后再處理。此時(shí)會(huì)計(jì)算總高度
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
skippedMeasure = true;
} else {
int oldHeight = Integer.MIN_VALUE;
if (lp.height == 0 && lp.weight > 0) {
//子控件高度為0并且weight>0,并且父控件是wrap_content帘撰,或者mode為UNSPECIFIED
//這時(shí)候父控件的高度是wrap_content跑慕,所以隨著子控件的高度進(jìn)行變化的
//顧強(qiáng)制將子控件高度設(shè)置為wrap_content,防止子控件高度為0
oldHeight = 0;
lp.height = LayoutParams.WRAP_CONTENT;
}
//方法名可知是對(duì)子控件進(jìn)行測(cè)量
measureChildBeforeLayout(
child, i, widthMeasureSpec, 0, heightMeasureSpec,
totalWeight == 0 ? mTotalLength : 0);
if (oldHeight != Integer.MIN_VALUE) {
lp.height = oldHeight;
}
final int childHeight = child.getMeasuredHeight();
final int totalLength = mTotalLength;
//比較child測(cè)量前后的總高度摧找,取大值
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
//當(dāng)設(shè)置權(quán)重最小尺寸的對(duì)象為true核行,獲取子View中最高高度
if (useLargestChild) {
largestChildHeight = Math.max(childHeight, largestChildHeight);
}
}
//計(jì)算baseline額外的偏移量,后面會(huì)用到
if ((baselineChildIndex >= 0) && (baselineChildIndex == i + 1)) {
mBaselineChildTop = mTotalLength;
}
//當(dāng)設(shè)置的基準(zhǔn)線對(duì)齊的對(duì)象index 大于 子對(duì)象的Index 并且 weight > 0 會(huì)報(bào)異常
if (i < baselineChildIndex && lp.weight > 0) {
throw new RuntimeException("A child of LinearLayout with index "
+ "less than mBaselineAlignedChildIndex has weight > 0, which "
+ "won't work. Either remove the weight, or don't set "
+ "mBaselineAlignedChildIndex.");
}
// 當(dāng)父類(LinearLayout)不是match_parent或者精確值的時(shí)候蹬耘,但子控件卻是一個(gè)match_parent
// 那么matchWidthLocally和matchWidth置為true
// 意味著這個(gè)控件將會(huì)占據(jù)父類(水平方向)的所有空間
boolean matchWidthLocally = false;
if (widthMode != MeasureSpec.EXACTLY && lp.width == LayoutParams.MATCH_PARENT) {
matchWidth = true;
matchWidthLocally = true;
}
final int margin = lp.leftMargin + lp.rightMargin;
final int measuredWidth = child.getMeasuredWidth() + margin;
//后面幾個(gè)就是給變量賦值
maxWidth = Math.max(maxWidth, measuredWidth);
childState = combineMeasuredStates(childState, child.getMeasuredState());
allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT;
if (lp.weight > 0) {
weightedMaxWidth = Math.max(weightedMaxWidth,
matchWidthLocally ? margin : measuredWidth);
} else {
alternativeMaxWidth = Math.max(alternativeMaxWidth,
matchWidthLocally ? margin : measuredWidth);
}
i += getChildrenSkipCount(child, i);
}
}
(3).測(cè)量Part2
<p>
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//...接上面的方法
//判斷showDivider值是否為end芝雪,是的情況下加上divider的高度
if (mTotalLength > 0 && hasDividerBeforeChildAt(count)) {
mTotalLength += mDividerHeight;
}
if (useLargestChild &&
(heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED)) {
//當(dāng)設(shè)置權(quán)重最小尺寸的對(duì)象為true
//并且LinearLayout是wrap_content,或者mode為UNSPECIFIED
//計(jì)算新的mTotalLength婆赠,因?yàn)檫@時(shí)候所有子控件都是用最大控件的最小值
mTotalLength = 0;
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
if (child == null) {
mTotalLength += measureNullChild(i);
continue;
}
if (child.getVisibility() == GONE) {
i += getChildrenSkipCount(child, i);
continue;
}
final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)
child.getLayoutParams();
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + largestChildHeight +
lp.topMargin + lp.bottomMargin + getNextLocationOffset(child));
}
}
//下面是計(jì)算屏幕除去所有子控件所占高度剩余的高度
//為了定義權(quán)重的子控件計(jì)算高度
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
int delta = heightSize - mTotalLength;
}
(3).測(cè)量Part3
<p>
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//...接上面的方法
if (skippedMeasure || delta != 0 && totalWeight > 0.0f) {
//這里skippedMeasure是接的上面測(cè)量Part1绵脯,當(dāng)父控件為match_parent,子控件height =0 ,weight>0的情況下skippedMeasure為true
//這里獲取總權(quán)重,當(dāng)我們?cè)O(shè)置了總權(quán)重則用我們?cè)O(shè)置的權(quán)重值休里,如果沒有設(shè)置蛆挫,則用子控件權(quán)重相加的和
float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight;
mTotalLength = 0;
for (int i = 0; i < count; ++i) {
//遍歷子View,根據(jù)權(quán)重對(duì)子View進(jìn)行測(cè)量
final View child = getVirtualChildAt(i);
if (child.getVisibility() == View.GONE) {
continue;
}
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
float childExtra = lp.weight;
if (childExtra > 0) {
//當(dāng)子控件的weight大于0時(shí)
int share = (int) (childExtra * delta / weightSum);
weightSum -= childExtra;
delta -= share;
final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
mPaddingLeft + mPaddingRight +
lp.leftMargin + lp.rightMargin, lp.width);
if ((lp.height != 0) || (heightMode != MeasureSpec.EXACTLY)) {
int childHeight = child.getMeasuredHeight() + share;
if (childHeight < 0) {
childHeight = 0;
}
//定義權(quán)重子控件重新測(cè)量妙黍,這時(shí)候childWidth是子控件本身的高度加上通過權(quán)重計(jì)算的額外高度
child.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));
} else {
//沒有定義權(quán)重子控件重新測(cè)量悴侵,當(dāng)額外高度大于0,則以這個(gè)額外高度為子控件的高度
child.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(share > 0 ? share : 0,
MeasureSpec.EXACTLY));
}
childState = combineMeasuredStates(childState, child.getMeasuredState()
& (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
}
final int margin = lp.leftMargin + lp.rightMargin;
final int measuredWidth = child.getMeasuredWidth() + margin;
maxWidth = Math.max(maxWidth, measuredWidth);
boolean matchWidthLocally = widthMode != MeasureSpec.EXACTLY &&
lp.width == LayoutParams.MATCH_PARENT;
alternativeMaxWidth = Math.max(alternativeMaxWidth,
matchWidthLocally ? margin : measuredWidth);
allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT;
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredHeight() +
lp.topMargin + lp.bottomMargin + getNextLocationOffset(child));
}
mTotalLength += mPaddingTop + mPaddingBottom;
} else {
alternativeMaxWidth = Math.max(alternativeMaxWidth,
weightedMaxWidth);
//當(dāng)設(shè)置了權(quán)重最小尺寸
if (useLargestChild && heightMode != MeasureSpec.EXACTLY) {
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null || child.getVisibility() == View.GONE) {
continue;
}
final LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();
float childExtra = lp.weight;
//子控件設(shè)置權(quán)重后拭嫁,就會(huì)以最大子元素的最小尺寸作為高度
if (childExtra > 0) {
child.measure(
MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(),
MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(largestChildHeight,
MeasureSpec.EXACTLY));
}
}
}
}
if (!allFillParent && widthMode != MeasureSpec.EXACTLY) {
maxWidth = alternativeMaxWidth;
}
maxWidth += mPaddingLeft + mPaddingRight;
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
if (matchWidth) {
forceUniformWidth(count, heightMeasureSpec);
}
}
到這里測(cè)量Vertical就結(jié)束了可免,接下來(lái)介紹下Layout的過程
2.layout流程
<p>
與measure一樣layout同樣是分兩個(gè)流程
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mOrientation == VERTICAL) {
layoutVertical(l, t, r, b);
} else {
layoutHorizontal(l, t, r, b);
}
}
同樣我們?nèi)ayoutVertical來(lái)進(jìn)行分析,layoutVertical相對(duì)代碼不是很多做粤,就不拆分分析了
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
int childTop;
int childLeft;
final int width = right - left;
int childRight = width - mPaddingRight;
//子控件可用的空間
int childSpace = width - paddingLeft - mPaddingRight;
final int count = getVirtualChildCount();
final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
//根據(jù)LinearLayout的對(duì)其方式浇借,設(shè)置第一個(gè)子控件的Top值
switch (majorGravity) {
case Gravity.BOTTOM:
childTop = mPaddingTop + bottom - top - mTotalLength;
break;
case Gravity.CENTER_VERTICAL:
childTop = mPaddingTop + (bottom - top - mTotalLength) / 2;
break;
case Gravity.TOP:
default:
childTop = mPaddingTop;
break;
}
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
final LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();
int gravity = lp.gravity;
if (gravity < 0) {
gravity = minorGravity;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
//根據(jù)子控件的對(duì)其方式設(shè)置left值
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = paddingLeft + ((childSpace - childWidth) / 2)
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = childRight - childWidth - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = paddingLeft + lp.leftMargin;
break;
}
//當(dāng)有設(shè)置分隔條,需要加上分隔條的高度
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
//子控件top遞增
childTop += lp.topMargin;
//用setChildFrame()方法設(shè)置子控件控件的在父控件上的坐標(biāo)軸
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
3.draw流程
<p>
最后說下draw流程怕品,draw流程相對(duì)來(lái)說沒有什么內(nèi)容妇垢,
protected void onDraw(Canvas canvas) {
if (mDivider == null) {
return;
}
if (mOrientation == VERTICAL) {
drawDividersVertical(canvas);
} else {
drawDividersHorizontal(canvas);
}
}
measure和layout將子控件的位置和大小確定后當(dāng)有設(shè)置分隔條則分為兩種流程繪制分隔條
void drawDividersVertical(Canvas canvas) {
final int count = getVirtualChildCount();
//當(dāng)分割線位置設(shè)置begin與middle走下面流程
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child != null && child.getVisibility() != GONE) {
if (hasDividerBeforeChildAt(i)) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int top = child.getTop() - lp.topMargin - mDividerHeight;
drawHorizontalDivider(canvas, top);
}
}
}
//當(dāng)分割線位置設(shè)置end走下面流程
if (hasDividerBeforeChildAt(count)) {
final View child = getLastNonGoneChild();
int bottom = 0;
if (child == null) {
bottom = getHeight() - getPaddingBottom() - mDividerHeight;
} else {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
bottom = child.getBottom() + lp.bottomMargin;
}
drawHorizontalDivider(canvas, bottom);
}
}
至此,LinearLayout的核心代碼就分析完成了
大家可以結(jié)合LinearLayout的屬性來(lái)進(jìn)行更深刻的理解H饪怠4彻馈!