在Android中,写Layout文件时,用到最多的就是FrameLayout,LinearLayout,Relative,今天我们来分析一下
特点:
1)FrameLayout 是层级布局,即所有的子View都是从底层向上层开始,默认不指定margin或者layout_gravity的话,每个子view的坐标其实坐标都是Framelayout的其实坐标
2)LinearLayout 线性布局,分为水平方向和垂直方向, 水平方向是从左到右开始,垂直方向是从上到下开始,复杂的布局情况下,可能会出线很多的嵌套
3)RelativeLayout 相对布局,每个子View都是相对父布局或其他的子View进行位置的安放,一定程度上,可减少布局层级嵌套
下面我们从源码的角度来分析这三种布局
上面三种布局,归根结底还是ViewGroup,它们的作用主要是用来测量子view大小,设置子view的显示坐标,以及绘制子view,
它们在绘制这一部分没有区别,所有的区别都在mearsure和layout过程,下面我们就针对这三种布局的mearsure和layout进行分析
1) FrameLayout
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
//判断FrameLayout 宽 高 是否同时设置了Match_parent或者 设置了指定大小的宽高
// measureMatchParentChildren 为 true,则表示没有设置了Match_parent或者 设置了指定大小的宽高
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
//下面这个循环就是计算出所有的子View中的最大宽度 maxWidth 和最大高度 maxHeight
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
// 计算子View的宽高,包含了子View的左右上下Margin,
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth,
child.get