LinearLayout属性用法和源码分析
作者:前世小书童
链接:http://www.jianshu.com/p/650c3fd7e6ab
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
对于一个View(ViewGroup)来说实现无非于三个流程,onMeasure(测量),onLayout(定位),onDraw(绘制),接下来就对这三个部分一一分析
但是首先还是对LinearLayout变量进行介绍
1.LinearLayout变量
其实LinearLayout变量与上篇属性篇中关联比较大,这里就直接上代码和注释了
//基准线对齐变量,默认为true
private boolean mBaselineAligned = true;
//基准线对齐的对象index
private int mBaselineAlignedChildIndex = -1;
//baseline额外的偏移量
private int mBaselineChildTop = 0;
//linearlayout的排列方式
private int mOrientation;
//linearlayout的对齐方式
private int mGravity = Gravity.START | Gravity.TOP;
//测量的时候通过累加得到所有子控件的高度和(Vertical)或者宽度和(Horizontal) ;
private int mTotalLength;
//权重总和变量
private float mWeightSum;
//权重最小尺寸的对象
private boolean mUseLargestChild;
//基准线对其相关
private int[] mMaxAscent;
private int[] mMaxDescent;
//分隔条相关
private Drawable mDivider;
private int mDividerWidth;
private int mDividerHeight;
private int mShowDividers;
private int mDividerPadding;
2.measure流程
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
当我们设置不同的orientation就会进入不同的测量流程,我们以其中的一个测量流程为例子进行说明,那么另外的测量流程也就不难理解了
我们以measureVertical为例来分析
由于代码相对比较长,所以根据不同的功能分段分析
(1).变量
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//mTotalLength为 LinearLayout的成员变量,在这里指的是所有子控件的高度和
mTotalLength = 0;
//所有子控件中宽度最大的值
int maxWidth = 0;
//子控件的测量状态
int childState = 0;
//子控件中layout_weight<=0的View最大高度
int alternativeMaxWidth = 0;
//子控件中layout_weight>0的View最大高度
int weightedMaxWidth = 0;
//子控件是否全是match_parent
boolean allFillParent = true;
//子控件所有layout_weight的和
float totalWeight = 0;
//获取子控件数量
final int count = getVirtualChildCount();
//获取测量模式
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//当子控件为match_parent的时候,该值为ture
boolean matchWidth = false;
boolean skippedMeasure = false;
//基准线对齐的对象index
final int baselineChildIndex = mBaselineAlignedChildIndex;
//权重最小尺寸的对象
final boolean useLargestChild = mUseLargestChild;
//子View中最高高度
int largestChildHeight = Integer.MIN_VALUE;
}
(2).测量Part1
其实这段代码前面自带的注释就很好说明接下来这一段代码做的事情了,
See how tall everyone is. Also remember max width.
就不对这句话进行翻译了,接下来看这一段代码做了什么事情
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//...接上面的变量
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
//这个不解释了,measureNullChild获得的结果是0
if (child == null) {
mTotalLength += measureNullChild(i);
continue;
}
//这个也不解释了
if (child.getVisibility() == View.GONE) {
i += getChildrenSkipCount(child, i);
continue;
}
// 根据showDivider的值(before/middle/end)来决定遍历到当前子控件时,高度是否需要加上divider的高度
// 比如showDivider为before,那么只会在第0个子控件测量时加上divider高度,其余情况下都不加
//这里测量不包括end的情况
if (hasDividerBeforeChildAt(i)) {
mTotalLength += mDividerHeight;
}
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
//根据子控件的权重得到总权重
totalWeight += lp.weight;
// 测量模式有三种:
// * UNSPECIFIED:父控件对子控件无约束
// * Exactly:父控件对子控件强约束,子控件永远在父控件边界内,越界则裁剪。如果要记忆的话,可以记忆为有对应的具体数值或者是Match_parent
// * AT_Most:子控件为wrap_content的时候,测量值为AT_MOST。
if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
//父控件高度为match_parent且子控件高度为0,weight>0情况下
// 测量到这里的时候,会给个标志位,稍后再处理。此时会计算总高度
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
//这时候父控件的高度是wrap_content,所以随着子控件的高度进行变化的
//顾强制将子控件高度设置为wrap_content,防止子控件高度为0
oldHeight = 0;
lp.height = LayoutParams.WRAP_CONTENT;
}
//方法名可知是对子控件进行测量
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测量前后的总高度,取大值
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
//当设置权重最小尺寸的对象为true,获取子View中最高高度
if (useLargestChild) {
largestChildHeight = Math.max(childHeight, largestChildHeight);
}
}
//计算baseline额外的偏移量,后面会用到
if ((baselineChildIndex >= 0) && (baselineChildIndex == i + 1)) {
mBaselineChildTop = mTotalLength;
}
//当设置的基准线对齐的对象index 大于 子对象的Index 并且 weight > 0 会报异常
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.");
}
// 当父类(LinearLayout)不是match_parent或者精确值的时候,但子控件却是一个match_parent
// 那么matchWidthLocally和matchWidth置为true
// 意味着这个控件将会占据父类(水平方向)的所有空间
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;
//后面几个就是给变量赋值
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).测量Part2
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)) {
//当设置权重最小尺寸的对象为true
//并且LinearLayout是wrap_content,或者mode为UNSPECIFIED
//计算新的mTotalLength,因为这时候所有子控件都是用最大控件的最小值
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));
}
}
//下面是计算屏幕除去所有子控件所占高度剩余的高度
//为了定义权重的子控件计算高度
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).测量Part3
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//...接上面的方法
if (skippedMeasure || delta != 0 && totalWeight > 0.0f) {
//这里skippedMeasure是接的上面测量Part1,当父控件为match_parent,子控件height =0 ,weight>0的情况下skippedMeasure为true
//这里获取总权重,当我们设置了总权重则用我们设置的权重值,如果没有设置,则用子控件权重相加的和
float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight;
mTotalLength = 0;
for (int i = 0; i < count; ++i) {
//遍历子View,根据权重对子View进行测量
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) {
//当子控件的weight大于0时
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;
}
//定义权重子控件重新测量,这时候childWidth是子控件本身的高度加上通过权重计算的额外高度
child.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));
} else {
//没有定义权重子控件重新测量,当额外高度大于0,则以这个额外高度为子控件的高度
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);
//当设置了权重最小尺寸
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;
//子控件设置权重后,就会以最大子元素的最小尺寸作为高度
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);
}
}
到这里测量Vertical就结束了,接下来介绍下Layout的过程
2.layout流程
与measure一样layout同样是分两个流程
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);
}
}
同样我们取layoutVertical来进行分析,layoutVertical相对代码不是很多,就不拆分分析了
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;
//根据LinearLayout的对其方式,设置第一个子控件的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);
//根据子控件的对其方式设置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;
}
//当有设置分隔条,需要加上分隔条的高度
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
//子控件top递增
childTop += lp.topMargin;
//用setChildFrame()方法设置子控件控件的在父控件上的坐标轴
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
3.draw流程
最后说下draw流程,draw流程相对来说没有什么内容,
protected void onDraw(Canvas canvas) {
if (mDivider == null) {
return;
}
if (mOrientation == VERTICAL) {
drawDividersVertical(canvas);
} else {
drawDividersHorizontal(canvas);
}
}
measure和layout将子控件的位置和大小确定后当有设置分隔条则分为两种流程绘制分隔条
void drawDividersVertical(Canvas canvas) {
final int count = getVirtualChildCount();
//当分割线位置设置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);
}
}
}
//当分割线位置设置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的核心代码就分析完成了
LinearLayout属性用法和源码分析的更多相关文章
- RxJava(一) create操作符的用法和源码分析
欢迎转载,转载请标明出处: http://blog.csdn.net/johnny901114/article/details/51524470 本文出自:[余志强的博客] 1 create操作符的基 ...
- 一文搞懂 CountDownLatch 用法和源码!
CountDownLatch 是多线程控制的一种工具,它被称为 门阀. 计数器或者 闭锁.这个工具经常用来用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用).下面我们就来一起 ...
- jQuery静态方法globalEval使用和源码分析
Eval函数大家都很熟悉,但是globalEval方法却很少使用,大多数参考手册也没有相关api,下面就对其用法和源码相应介绍: jQuery.globalEval()函数用于全局性地执行一段Java ...
- Quartz学习--二 Hello Quartz! 和源码分析
Quartz学习--二 Hello Quartz! 和源码分析 三. Hello Quartz! 我会跟着 第一章 6.2 的图来 进行同步代码编写 简单入门示例: 创建一个新的java普通工程 ...
- Android Debuggerd 简要介绍和源码分析(转载)
转载: http://dylangao.com/2014/05/16/android-debuggerd-%E7%AE%80%E8%A6%81%E4%BB%8B%E7%BB%8D%E5%92%8C%E ...
- Java并发编程(七)ConcurrentLinkedQueue的实现原理和源码分析
相关文章 Java并发编程(一)线程定义.状态和属性 Java并发编程(二)同步 Java并发编程(三)volatile域 Java并发编程(四)Java内存模型 Java并发编程(五)Concurr ...
- Kubernetes Job Controller 原理和源码分析(一)
概述什么是 JobJob 入门示例Job 的 specPod Template并发问题其他属性 概述 Job 是主要的 Kubernetes 原生 Workload 资源之一,是在 Kubernete ...
- Kubernetes Job Controller 原理和源码分析(二)
概述程序入口Job controller 的创建Controller 对象NewController()podControlEventHandlerJob AddFunc DeleteFuncJob ...
- Kubernetes Job Controller 原理和源码分析(三)
概述Job controller 的启动processNextWorkItem()核心调谐逻辑入口 - syncJob()Pod 数量管理 - manageJob()小结 概述 源码版本:kubern ...
随机推荐
- 01——微信小程序官方demo讲解——文件结构
1.环境概览 首先环境配置的部分略过,打开小程序开发工具.选择一个空目录,即可开始一个demo项目. 其中新建成功后的目录如图所示: 2.文件结构描述 如图所示,左边是界面展示,右边是目录结构. 目录 ...
- 局部加权线性回归(Locally weighted linear regression)
首先我们来看一个线性回归的问题,在下面的例子中,我们选取不同维度的特征来对我们的数据进行拟合. 对于上面三个图像做如下解释: 选取一个特征,来拟合数据,可以看出来拟合情况并不是很好,有些数据误差还是比 ...
- 利用Linux系统生成随机密码的9种方法
Linux操作系统的一大优点是对于同样一件事情,你可以使用高达数百种方法来实现它.例如,你可以通过数十种方法来生成随机密码.本文将介绍生成随机密码的十种方法. 1. 使用SHA算法来加密日期,并输出结 ...
- [Z]LaTeX入门教程
LaTeX入门教程 Contents TEX/LATEX是什么? 为什么要用TEX/LATEX? 安装 开始使用 数学符号使用中文文章的各个部分表格 行内公式与行间公式 上标与下标 常见的数学公式 行 ...
- openLayers 3 之入门
openLayers 3 之入门 openlayer是web GIS客户端开发提供的javascript类库,也是开源框架,可以加载本地数据进行展示地图 1.下载相关引用的js.css文件 2.类似于 ...
- c# typeof 与 Type.GetType 使用与效率对比
static void ReflectionTest() {//测试两种反射的效率问题 //Type.GetType()只能在同一个程序集中使用,typeof则可以跨程序集(assembly) //通 ...
- node模块示例
来源于慕课网课程:http://www.imooc.com/video/6701 (视频) 模块的流程图如下: 做一个学校的模块示例 建一个学生的js studet.js function add(s ...
- 572. Subtree of Another Tree 大树里包括小树
[抄题]: Given two non-empty binary trees s and t, check whether tree t has exactly the same structure ...
- Zedboard学习(三):PL下流水灯实验 标签: fpgazynqPL 2017-07-05 11:09 21人阅读 评论(0)
zynq系列FPGA分为PS部分和PL部分. PL: 可编程逻辑 (Progarmmable Logic), 就是FPGA部分. PS: 处理系统 (Processing System) , 就是与F ...
- jquery Ajax跨域请求
这是jquery api文档对跨域请求的解析:如果获取的数据文件存放在远程服务器上(域名不同,也就是跨域获取数据),则需要使用JSONP类型.使用这种类型的话,会创建一个查询字符串参数 callbac ...