1. 什么是布局阶段
ViewGroup摆放子View的位置
2.布局阶段原理
- 在父容器的onlayout()中根据在测量阶段测量出的子View的尺寸和自己的布局规则,计算出子View的绘制位置(left,top,right,bottom)
- 调用子View的layout(l,t,r,b)方法,View会记录下绘制的位置(应该是留给绘制的时候使用)。
- 在子View的layout方中如果会调用子View的onLayout 方法,如果子View是容器则onLayout中会重复1,2步,如果不是则onLayout没有任何实现
3.源码分析
父容器以AbsoluteLayout为例
public class AbsoluteLayout{
@Override
protected void onLayout(boolean changed, int l, int t,
int r, int b) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
AbsoluteLayout.LayoutParams lp =
(AbsoluteLayout.LayoutParams) child.getLayoutParams();
int childLeft = mPaddingLeft + lp.x;
int childTop = mPaddingTop + lp.y;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
}
View
pubic
public void layout(int l, int t, int r, int b) {
boolean changed =
public void layout(int l, int t, int r, int b) {
isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
onLayout(changed, l, t, r, b);
}
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
4.注意
- measure是调度方法,onMeasure确定视图的大小。
- layout确定视图的位置,onLayout确定子视图的位置。
- View.java和ViewGroup.java都没有实现onLayout
- View.java没有实现onLayout 是因为View.java没有子View
- ViewGroup.java没有实现onLayout则所用,所有继承ViewGroup的容器需要根据自己的规则计算子View的位置
网友评论