一直想研究下安卓各種布局控件,FrameLayout是安卓最簡單的界面布局,是以就從FrameLayout講起。
1.屬性。frameLayout繼承ViewGroup,除了擁有ViewGroup的屬性之外,隻有一個layout_gravity屬性。看它的内部靜态類LayoutParams:
public static class LayoutParams extends MarginLayoutParams {
public int gravity = -1;//唯一的屬性
2.繪制過程。首先,它會周遊所有子view,并且對每個子view進行measure,并記錄下子view的最大寬高,作為自身的尺寸。在這個過程中,如果自身是不确定大小的模式,子view又是MATCH_PARENT屬性的,就需要為這些子view重新測繪。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
(。。。。。。)
int maxHeight = 0;//記錄最大的寬高
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);//測繪所有子view
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);//儲存需要重新測繪的子view
}
}
}
}
(。。。。。。)
if (count > 1) {
for (int i = 0; i < count; i++) {
<pre name="code" class="java" style="font-size: 13.3333px;"> (。。。。。。)
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);//重新測繪子view } } }
3.layout過程。FrameLayout對每個子view的layout過程是相同的。它周遊所有子view,通過子view的gravity屬性進行xy軸偏移量的計算,最後調用child.layout()對子View進行布局。
void layoutChildren(int left, int top, int right, int bottom,
boolean forceLeftGravity) {
(。。。。。。)
for (int i = 0; i < count; i++) {
(。。。。。。)
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin;
break;
}
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = parentTop + lp.topMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}