Android自定义View
概述
Android开发进阶的必经之路
一个效果只要它能够在手机上面实现你就应该具备实现它的能力。
学习方式:实战->理论
为什么要自定义View
Android系统提供了一系列的原生控件,但这些原生控件并不能够满足我们的需求时,我们就需要自定义View了。
自定义View的基本方法
自定义View的最基本的三个方法分别是: onMeasure()、onLayout()、onDraw();
View在Activity中显示出来,要经历测量、布局和绘制三个步骤,分别对应三个动作:measure、layout和draw。
- 测量:onMeasure()决定View的大小;
- 布局:onLayout()决定View在ViewGroup中的位置;
- 绘制:onDraw()决定绘制这个View。
自定义View的分类
- 自定义View: 只需要重写onMeasure()和onDraw()
在没有现成的View,需要自己实现的时候,就使用自定义View,一般继承自View,SurfaceView或其他的View - 自定义ViewGroup: 则只需要重写onMeasure()和onLayout()
一般是利用现有的组件根据特定的布局方式来组成新的组件,大多继承自ViewGroup或各种Layout
自定义View基础
View的分类
视图View主要分为两类
类别 | 解释 | 特点 |
---|---|---|
单一视图 | 即一个View,如TextView | 不包含子View |
视图组 | 即多个View组成的ViewGroup,如LinearLayout | 包含子View |
View类简介
- View类是Android中各种组件的基类,如View是ViewGroup基类
- View表现为显示在屏幕上的各种视图
Android中的UI组件都由View、ViewGroup组成。
-
View的构造函数:共有4个
// 如果View是在Java代码里面new的,则调用第一个构造函数 public CarsonView(Context context) { super(context); } // 如果View是在.xml里声明的,则调用第二个构造函数 // 自定义属性是从AttributeSet参数传进来的 public CarsonView(Context context, AttributeSet attrs) { super(context, attrs); } // 不会自动调用 // 一般是在第二个构造函数里主动调用 // 如View有style属性时 public CarsonView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //API21之后才使用 // 不会自动调用 // 一般是在第二个构造函数里主动调用 // 如View有style属性时 public CarsonView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); }
AttributeSet与自定义属性
系统自带的View可以在xml中配置属性,对于写的好的自定义View同样可以在xml中配置属性,为了使自定义的View的属性可以在xml中配置,需要以下4个步骤:
- 通过
<declare-styleable>
为自定义View添加属性 - 在xml中为相应的属性声明属性值
- 在运行时(一般为构造函数)获取属性值
- 将获取到的属性值应用到View
View视图层级结构
- PhoneWindow是Android系统中最基本的窗口系统,继承自Windows类,负责管理界面显示以及事件响应。它是Activity与View系统交互的接口
- DecorView是PhoneWindow中的起始节点View,继承于View类,作为整个视图容器来使用。用于设置窗口属性。它本质上是一个FrameLayout
- ViewRoot在Activtiy启动时创建,负责管理、布局、渲染窗口UI等等
对于多View的视图,结构是树形结构:最顶层是ViewGroup,ViewGroup下可能有多个ViewGroup或View,如下图:
一定要记住:无论是measure过程、layout过程还是draw过程,永远都是从View树的根节点开始测量或计算(即从树的顶端开始),一层一层、一个分支一个分支地进行(即树形递归),最终计算整个View树中各个View,最终确定整个View树的相关属性。
Android坐标系
Android的坐标系定义为:
- 屏幕的左上角为坐标原点
- 向右为x轴增大方向
- 向下为y轴增大方向
区别于一般的数学坐标系
Android两种坐标系
屏幕坐标系和视图坐标系:
View的位置描述(采用视图坐标系)
View的位置由4个顶点决定的
4个顶点的位置描述分别由4个值决定:
请记住:View的位置是相对于父控件而言的
- Top:子View上边界到父view上边界的距离
- Left:子View左边界到父view左边界的距离
- Bottom:子View下边距到父View上边界的距离
- Right:子View右边界到父view左边界的距离
View的位置获取方式
View的位置是通过view.getxxx()函数进行获取:(以Top为例)
// 获取Top位置
public final int getTop() {
return mTop;
}
// 其余如下:
getLeft(); //获取子View左上角距父View左侧的距离
getBottom(); //获取子View右下角距父View顶部的距离
getRight(); //获取子View右下角距父View左侧的距离
与MotionEvent中 get()和getRaw()的区别:
//get() :触摸点相对于其所在组件坐标系的坐标
event.getX();
event.getY();
//getRaw() :触摸点相对于屏幕默认坐标系的坐标
event.getRawX();
event.getRawY();
Android中颜色相关内容
Android支持的颜色模式:
以ARGB8888为例介绍颜色定义:
View树的绘制流程
View树的绘制流程是谁负责的?
view树的绘制流程是通过ViewRoot去负责绘制的,ViewRoot这个类的命名有点坑,最初看到这个名字,翻译过来是view的根节点,但是事实完全不是这样,ViewRoot其实不是View的根节点,它连view节点都算不上,它的主要作用是View树的管理者,负责将DecorView和PhoneWindow“组合”起来,而View树的根节点严格意义上来说只有DecorView;每个DecorView都有一个ViewRoot与之关联,这种关联关系是由WindowManager去进行管理的;
view的添加
view的绘制流程
所以,自定义View任督二脉就在于此:
自定义View主要是实现 onMeasure + onDraw
自定义ViewGroup主要是实现 onMeasure + onLayout
测量的整体流程:先测量子View的大小,再测量自己的大小:
measure过程
- 系统为什么要有measure过程?
- measure过程都干了点什么事?
- 对于自适应的尺寸机制,如何合理的测量一颗View树?
- 那么ViewGroup是如何向子View传递限制信息的?
- ScrollView嵌套ListView问题?
View.requestLayout():
layout过程
- 系统为什么要有layout过程?
- layout过程都干了点什么事?
View.performLayout():
draw过程
- 系统为什么要有draw过程?
- draw过程都干了点什么事?
canvas, paint,matrix,clip,rect,path,line,text,animation
View.invalidate():
LayoutParams
LayoutParams翻译过来就是布局参数,子View通过LayoutParams告诉父容器(ViewGroup)应该如何放置自己。从这个定义中也可以看出来LayoutParams与ViewGroup是息息相关的,因此脱离ViewGroup谈LayoutParams是没有意义的。
事实上,每个ViewGroup的子类都有自己对应的LayoutParams类,典型的如LinearLayout.LayoutParams和FrameLayout.LayoutParams等,可以看出来LayoutParams都是对应ViewGroup子类的内部类
MarginLayoutParams
MarginLayoutParams是和外间距有关的。事实也确实如此,和LayoutParams相比,MarginLayoutParams只是增加了对上下左右外间距的支持。实际上大部分LayoutParams的实现类都是继承自MarginLayoutParams,因为基本所有的父容器都是支持子View设置外间距的
- 属性优先级问题
MarginLayoutParams主要就是增加了上下左右4种外间距。在构造方法中,先是获取了margin属性;如果该值不合法,就获取horizontalMargin;如果该值不合法,再去获取leftMargin和rightMargin属性(verticalMargin、topMargin和bottomMargin同理)。我们可以据此总结出这几种属性的优先级
margin > horizontalMargin和verticalMargin > leftMargin和RightMargin、topMargin和bottomMargin
- 属性覆盖问题
优先级更高的属性会覆盖掉优先级较低的属性。此外,还要注意一下这几种属性上的注释
Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
LayoutParams与View如何建立联系
- 在XML中定义View
- 在Java代码中直接生成View对应的实例对象
addView
//ViewGroup.java
/**
* 重载方法1:添加一个子View
* 如果这个子View还没有LayoutParams,就为子View设置当前ViewGroup默认的LayoutParams
*/
public void addView(View child) {
addView(child, -1);
}
/**
* 重载方法2:在指定位置添加一个子View
* 如果这个子View还没有LayoutParams,就为子View设置当前ViewGroup默认的LayoutParams
* @param index View将在ViewGroup中被添加的位置(-1代表添加到末尾)
*/
public void addView(View child, int index) {
if (child == null) {
throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
}
LayoutParams params = child.getLayoutParams();
if (params == null) {
params = generateDefaultLayoutParams();// 生成当前ViewGroup默认的LayoutParams
if (params == null) {
throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
}
}
addView(child, index, params);
}
/**
* 重载方法3:添加一个子View
* 使用当前ViewGroup默认的LayoutParams,并以传入参数作为LayoutParams的width和height
*/
public void addView(View child, int width, int height) {
final LayoutParams params = generateDefaultLayoutParams(); // 生成当前ViewGroup默认的LayoutParams
params.width = width;
params.height = height;
addView(child, -1, params);
}
/**
* 重载方法4:添加一个子View,并使用传入的LayoutParams
*/
@Override
public void addView(View child, LayoutParams params) {
addView(child, -1, params);
}
/**
* 重载方法4:在指定位置添加一个子View,并使用传入的LayoutParams
*/
public void addView(View child, int index, LayoutParams params) {
if (child == null) {
throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
}
// addViewInner() will call child.requestLayout() when setting the new LayoutParams
// therefore, we call requestLayout() on ourselves before, so that the child's request
// will be blocked at our level
requestLayout();
invalidate(true);
addViewInner(child, index, params, false);
}
private void addViewInner(View child, int index, LayoutParams params,
boolean preventRequestLayout) {
.....
if (mTransition != null) {
mTransition.addChild(this, child);
}
if (!checkLayoutParams(params)) { // ① 检查传入的LayoutParams是否合法
params = generateLayoutParams(params); // 如果传入的LayoutParams不合法,将进行转化操作
}
if (preventRequestLayout) { // ② 是否需要阻止重新执行布局流程
child.mLayoutParams = params; // 这不会引起子View重新布局(onMeasure->onLayout->onDraw)
} else {
child.setLayoutParams(params); // 这会引起子View重新布局(onMeasure->onLayout->onDraw)
}
if (index < 0) {
index = mChildrenCount;
}
addInArray(child, index);
// tell our children
if (preventRequestLayout) {
child.assignParent(this);
} else {
child.mParent = this;
}
.....
}
自定义LayoutParams
1.创建自定义属性
<resources>
<declare-styleable name="xxxViewGroup_Layout">
<!-- 自定义的属性 -->
<attr name="layout_simple_attr" format="integer"/>
<!-- 使用系统预置的属性 -->
<attr name="android:layout_gravity"/>
</declare-styleable>
</resources>
2.继承MarginLayoutParams
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
public int simpleAttr;
public int gravity;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
// 解析布局属性
TypedArray typedArray = c.obtainStyledAttributes(attrs, R.styleable.SimpleViewGroup_Layout);
simpleAttr = typedArray.getInteger(R.styleable.SimpleViewGroup_Layout_layout_simple_attr, 0);
gravity=typedArray.getInteger(R.styleable.SimpleViewGroup_Layout_android_layout_gravity, -1);
typedArray.recycle();//释放资源
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
3.重写几个从ViewGroup中继承来的与LayoutParams相关的方法
// 检查LayoutParams是否合法
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof SimpleViewGroup.LayoutParams;
}
// 生成默认的LayoutParams
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new SimpleViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
// 对传入的LayoutParams进行转化
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new SimpleViewGroup.LayoutParams(p);
}
// 对传入的LayoutParams进行转化
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new SimpleViewGroup.LayoutParams(getContext(), attrs);
}
LayoutParams常见的子类
在为View设置LayoutParams的时候需要根据它的父容器选择对应的LayoutParams,否则结果可能与预期不一致,这里简单罗列一些常见的LayoutParams子类:
- ViewGroup.MarginLayoutParams
- FrameLayout.LayoutParams
- LinearLayout.LayoutParams
- RelativeLayout.LayoutParams
- RecyclerView.LayoutParams
- GridLayoutManager.LayoutParams
- StaggeredGridLayoutManager.LayoutParams
- ViewPager.LayoutParams
- WindowManager.LayoutParams
MeasureSpec
MeasureSpec是View中的内部类,基本都是二进制运算。由于int是32位的,用高两位表示mode,低30位表示size,MODE_SHIFT = 30的作用是移位
UNSPECIFIED:不对View大小做限制,系统使用
EXACTLY:确切的大小,如:100dp
AT_MOST:大小不可超过某数值,如:matchParent, 最大不能超过你爸爸
定义
测量规格,封装了父容器对 view 的布局上的限制,内部提供了宽高的信息( SpecMode 、 SpecSize ),SpecSize是指在某种SpecMode下的参考尺寸,其中SpecMode 有如下三种:
- UNSPECIFIED
父控件不对你有任何限制,你想要多大给你多大,想上天就上天。这种情况一般用于系统内部,表示一种测量状态。(这个模式主要用于系统内部多次Measure的情形,并不是真的说你想要多大最后就真有多大) - EXACTLY
父控件已经知道你所需的精确大小,你的最终大小应该就是这么大。 - AT_MOST
你的大小不能大于父控件给你指定的size,但具体是多少,得看你自己的实现。
MeasureSpec的意义
通过将 SpecMode 和 SpecSize 打包成一个 int 值可以避免过多的对象内存分配,为了方便操作,其提供了打包 / 解包方法
MeasureSpec值的确定
MeasureSpec值到底是如何计算得来的呢?
子View的MeasureSpec值是根据子View的布局参数(LayoutParams)和父容器的MeasureSpec值计算得来的,具体计算逻辑封装在getChildMeasureSpec()里
/**
*
* 目标是将父控件的测量规格和child view的布局参数LayoutParams相结合,得到一个
* 最可能符合条件的child view的测量规格。
* @param spec 父控件的测量规格
* @param padding 父控件里已经占用的大小
* @param childDimension child view布局LayoutParams里的尺寸
* @return child view 的测量规格
*/
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) {
// 当父控件的测量模式 是 精确模式,也就是有精确的尺寸了
case MeasureSpec.EXACTLY:
//如果child的布局参数有固定值,比如"layout_width" = "100dp"
//那么显然child的测量规格也可以确定下来了,测量大小就是100dp,测量模式也是EXACTLY
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
}
//如果child的布局参数是"match_parent",也就是想要占满父控件
//而此时父控件是精确模式,也就是能确定自己的尺寸了,那child也能确定自己大小了
else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
}
//如果child的布局参数是"wrap_content",也就是想要根据自己的逻辑决定自己大小,
//比如TextView根据设置的字符串大小来决定自己的大小
//那就自己决定呗,不过你的大小肯定不能大于父控件的大小嘛
//所以测量模式就是AT_MOST,测量大小就是父控件的size
else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// 当父控件的测量模式 是 最大模式,也就是说父控件自己还不知道自己的尺寸,但是大小不能超过size
case MeasureSpec.AT_MOST:
//同样的,既然child能确定自己大小,尽管父控件自己还不知道自己大小,也优先满足孩子的需求
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
}
//child想要和父控件一样大,但父控件自己也不确定自己大小,所以child也无法确定自己大小
//但同样的,child的尺寸上限也是父控件的尺寸上限size
else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
//child想要根据自己逻辑决定大小,那就自己决定呗
else if (childDimension == LayoutParams.WRAP_CONTENT) {
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 = 0;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
针对上表,这里再做一下具体的说明
- 对于应用层 View ,其 MeasureSpec 由父容器的 MeasureSpec 和自身的 LayoutParams 来共同决定
- 对于不同的父容器和view本身不同的LayoutParams,view就可以有多种MeasureSpec。
1. 当view采用固定宽高的时候,不管父容器的MeasureSpec是什么,view的MeasureSpec都是精确模式并且其大小遵循Layoutparams中的大小;
2. 当view的宽高是match_parent时,这个时候如果父容器的模式是精准模式,那么view也是精准模式并且其大小是父容器的剩余空间,如果父容器是最大模式,那么view也是最大模式并且其大小不会超过父容器的剩余空间;
3. 当view的宽高是wrap_content时,不管父容器的模式是精准还是最大化,view的模式总是最大化并且大小不能超过父容器的剩余空间。
4. Unspecified模式,这个模式主要用于系统内部多次measure的情况下,一般来说,我们不需要关注此模式(这里注意自定义View放到ScrollView的情况 需要处理)。
getChildMeasureSpec()计算出来的MeasureSpec 是一个理论参考值,具体要等子View进行measure过程测量完成后自己的大小才能确定。
getChildMeasureSpec()的第二个参数padding表示当前View的padding,所以计算子View的大小时要减去相应的padding表示的数值。
MeasureSpec.UNSPECIFIED在什么场景使用?
MesureSpec.UNSPECIFIED
- 这个模式什么时候会遇到?
- 遇到后怎么处理?
- 有什么注意事项?
UNSPECIFID,就是未指定的意思,在这个模式下父控件不会干涉子 View 想要多大的尺寸。
那么,这个模式什么时候会onMeasure() 里遇到呢?其实是取决于它的父容器。
就拿最常用的 RecyclerView 做例子,在 Item 进行 measure() 时,如果列表可滚动,并且 Item 的宽或高设置了 wrap_content 的话,那么接下来,itemView 的 onMeasure( )方法的测量模式就会变成 MeasureSpec.UNSPECIFIED。
我们不妨打开 RecyclerView 源码,会在 getChildMeasureSpec() 方法里看到这么一句注释:
MATCH_PARENT can’t be applied since we can scroll in this dimension, wrap instead using UNSPECIFIED.
它想表达的是:在可滚动的ViewGroup中,不应该限制 Item 的尺寸(如果是水平滚动,就不限制宽度),为什么呢? 因为是可以滚动的,不管 Item 有多宽,有多高,通过滚动也一样能看到滚动前被遮挡的部分。
有同学可能会有疑问: 我设置 wrap_content,在 onMeasure() 中应该收到的是 AT_MOST 才对啊,为什么要强制变成 UNSPECIFIED?
这是因为考虑到 Item 的尺寸有可能超出这个可滚动的 ViewGroup 的尺寸,而在 AT_MOST 模式下,你的尺寸不能超出你所在的 ViewGroup 的尺寸,最多只能等于,所以用 UNSPECIFIED会更合适,这个模式下你想要多大就多大。
那么,我们在自定义 View 的时候,在测量时发现是 UNSPECIFIED 模式时,应该怎么做呢?
这个就比较自由了,既然尺寸由自己决定,那么我可以写死为 50,也可以固定为 200。但还是建议结合实际需求来定义咯。
比如 ImageView,它的做法就是:有设置图片内容(drawable)的话,会直接使用这个 drawable 的尺寸,但不会超过指定的 MaxWidth 或 MaxHeight, 没有内容的话就是 0。而 TextView 处理 UNSPECIFIED 的方式,和 AT_MOST 是一样的。
当然了,这些尺寸都不一定等于最后 layout 出来的尺寸,因为最后决定子 View 位置和大小的,是在 onLayout() 方法中,在这里你完全可以无视这些尺寸,去 layout()成自己想要的样子。不过,一般不会这么做。
item高度无效?
ViewPager,RecyclerView、ListView创建item时都有这个问题,即item布局文件中设置了高度值后无效。
原因:
inflate只有root参数设置了item的父布局并且attachToRoot参数设置为false,才会将item设置的布局参数设置进去。
错误写法:
View view = LayoutInflater.from(mContext).inflate(R.layout.linear_item, null);
正确写法:
View view = LayoutInflater.from(mContext).inflate(R.layout.linear_item, container, false);
注意:所有的适配器类型的View(ViewPager,RecyclerView、ListView)创建item时都用这种写法,那
View view = LayoutInflater.from(mContext).inflate(R.layout.linear_item, null);
这种写法什么时候使用?系统创建DecorView时使用,DecorView是根布局,它没有父布局,所以root参数设置为null。
ViewPager设置wrap_content无效
问题描述:
开发中ViewPager设置高度为wrap_content,然后在ItemView中固定高度,发现ViewPager并不能自适应调整高度,总是会占满可以用的布局,效果和match_parent一样。
问题分析:
查看ViewPager的源码
//ViewPager.java
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// For simple implementation, our internal size is always 0.
// We depend on the container to specify the layout size of
// our view. We can't really know what it is since we will be
// adding and removing different arbitrary views and do not
// want the layout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
final int measuredWidth = getMeasuredWidth();
final int maxGutterSize = measuredWidth / 10;
mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize);
...
}
从注释可以看到,ViewPager设置自己默认的size都是0,然后优先用父布局传过来的宽高,完全不考虑子view的属性,因为子View可以被动态的添加或删除,ViewPager希望此时不要改变自己的布局。
因此ViewPager的onMeasure()是不会进行测量子View的高度的,ViewPager设置的wrap_content自然无效。如果ViewPager设置了wrap_content,那么ViewPager的父布局在调用getChildMeasureSpec()计算ViewPager的MeasureSpec时得出的结果是:size=自己的size,mode=AT_MOST(假设ViewPager的父布局是固定大小),而ViewPager的onMeasure()方法直接根据父布局传递过来的heightMeasureSpec设置自己的高度,没有进行任何测量操作,因此ViewPager的size就是父布局的size。
根本原因就是:ViewPager的设计者设计ViewPager的目标就是针对整个页面的滑动切换进行设计的(从ViewPager的命名就可以看出),并不是用于banner滚动这种场景的,ViewPager设置wrap_content无效是使用场景不适合的原因,不是源码的bug,所以我们使用时想让ViewPager自适应子View的高度,需要进行处理。
问题解决方案:
从问题分析可以知道,要限制ViewPager的高度,不能靠ViewPager自身的wrap_content实现,可以设置固定高度值,也可以通过外部加一个父布局来限制高度,当然,如果非要使用wrap_content来自适应子View高度的话,可以重写onMeasure方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
Log.d(TAG, "onMeasure: getChildCount: " + getChildCount());
//遍历所有的子View,用传递过来的MeasureSpec以及子View的LayoutParams测量子View的高度,采用最高的子View的高度
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
//child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED));//错误的解决方法
ViewGroup.LayoutParams lp = child.getLayoutParams();
int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, 0, lp.width);
int childHightSpec = getChildMeasureSpec(heightMeasureSpec, 0, lp.height);
child.measure(childWidthSpec, childHightSpec);
int h = child.getMeasuredHeight();
if (h > height) {//采用最高的子View的高度
height = h;
}
Log.d(TAG, "onMeasure: " + h + " height: " + height);
}
//测量出孩子的高度后用这个高度计算自己的heightMeasureSpec
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
//这样调用super.onMeasure(widthMeasureSpec, heightMeasureSpec);之后ViewPager设置的高度就是自己子View的高度,而不是父容器的高度
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
FlowLayout流式布局
FlowLayout, 流式布局, 这个概念在移动端或者前端开发中很常见,特别是在多标签的展示中, 往往起到了关键的作用。然而Android 官方, 并没有为开发者提供这样一个布局。
流式布局项目实战
总体思路:先测量孩子,再测量自己。
绝大多数Layout都是先测量孩子,所有孩子的大小都测量完了,自己的大小也就确定了。但ViewPager例外,ViewPager是先测量自己的大小(setMeasuredDimension方法),然后再测量孩子的大小。
整体代码框架如下:
难点是childView的widthMeasureSpec和heightMeasureSpec两个参数怎么正确计算,并不能直接把自己的这两个参数直接给childView,以及自己的width和height怎么计算。
完成后的代码如下:
//度量
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//这里尽量不要创建对象,会有内存抖动
clearMeasureParams();//onMeasure()可能会调用多次,所以要在这里清空测量过程中保存的数据
//先度量孩子
int childCount = getChildCount();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int selfWidth = MeasureSpec.getSize(widthMeasureSpec); //ViewGroup解析的父亲给我的宽度
int selfHeight = MeasureSpec.getSize(heightMeasureSpec); // ViewGroup解析的父亲给我的高度
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();
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测量完成后,获取子view的度量宽高
int childMesauredWidth = childView.getMeasuredWidth();
int childMeasuredHeight = childView.getMeasuredHeight();
//如果需要换行
if (childMesauredWidth + lineWidthUsed + mHorizontalSpacing > selfWidth) {
//一旦换行,我们就可以判断当前行需要的宽和高了,所以此时要记录下来
allLines.add(lineViews);
lineHeights.add(lineHeight);
parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
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);
parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
}
}
}
//再度量自己,保存
//根据子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);
}
FlexboxLayout
https://www.jianshu.com/p/0723ff4123e1
FrameLayout
LinearLayout
常见面试题
LayoutParams 是什么?与MeasureSpec有关系吗?
对于DecorView,它的ViewMeasureSpec是由自己的LayoutParams决定的(因为屏幕的尺寸是已知的)
如果LayoutParams是Match_parent,那么是MeasureSpec.EXACTLY
如果LayoutParams是具体的dp,那么是MeasureSpec.EXACTLY
如果LayoutParams是wrap_content,那么是MeasureSpec.AT_MOST
对于普通View,View的MeasureSpec是由父View传递来的MeasureSpec和自己的LayoutParams决定的
MeasureSpec 是什么?
MeasureSpec是View中的内部类,基本都是二进制运算。由于int是32位的,用高两位表示mode,低30位表示size,MODE_SHIFT = 30的作用是移位。
UNSPECIFIED:不对View大小做限制,系统使用
EXACTLY:确切的大小,如:100dp
AT_MOST:大小不可超过某数值,如:matchParent, 最大不能超过你爸爸
MeasureSpecs 创建规则
为什么要measure?
开发人员在绘制UI的时候,基本都是通过XML布局文件的方式来配置UI,而每个View必须要设置的两个属性就是layout_width和layout_height,这两个属性代表着当前View的尺寸。
所以这两个属性的值是必须要指定的,这两个属性的取值只能为三种类型:
1、固定的大小,比如100dp。
2、刚好包裹其中的内容,wrap_content。
3、想要和父布局一样大,match_parent。
比如:
android:layout_width="10dp"
android:layout_width="match_parent"
android:layout_width="wrap_content"
试想一下,那如果这些属性只允许设置固定的大小,那么每个View的尺寸在绘制的时候就已经确定了,所以不需要measure过程。但是由于需要满足自适应尺寸的机制(wrap_content,match_parent),所以需要一个measure过程,measure过程就是把wrap_content和match_parent变为具体的尺寸数值的过程。只有通过measure过程,才能计算出View的大小数据,后面才能根据这些数据进行正确的布局和绘制。
getMeasureWidth与getWidth的区别
getMeasuredWidth:
/**
* Like {@link #getMeasuredWidthAndState()}, but only returns the
* raw width component (that is the result is masked by
* {@link #MEASURED_SIZE_MASK}).
*
* @return The raw measured width of this view.
*/
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
在measure()过程结束后就可以获取到对应的值;
mMeasuredWidth是通过setMeasuredDimension()方法来进行设置的.
getWidth:
/**
* Return the width of your view.
*
* @return The width of your view, in pixels.
*/
public final int getWidth() {
return mRight - mLeft;
}
在layout()过程结束后才能获取到;
是通过视图右边的坐标减去视图左边的坐标计算出来的.
为什么onMeasure 、onLayout 、onDraw会调用多次
先看下View的层次结构图:
View的onMeasure 方法是由父布局来调用的(父布局的onMeasure方法会调用child.measure进行子View的测量,measure方法会调用onMeasure),所以具体调用次数由父布局的onMeasure方法的测量算法决定,以FrameLayout为例:
FrameLayout的onMeasure方法会调用measureChildWithMargins()方法进行子View的测量,测量完成之后调用setMeasuredDimension()设置自己的大小,然后还会再次获取mMatchParentChildren里面的所有子View,调用child.measure再测量一次。