上一章我们已经增加了指定方向的attr.接下来,接下来我们来看一下,怎么横向测量和布局。
先晒一下我们的xml
<com.jhzl.customview.MineLineLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@color/black"
android:layout_gravity="center">
<EditText
android:background="@android:color/holo_red_dark"
android:text="hahah"
android:layout_width="200dp"
android:layout_height="@dimen/dp100"/>
<EditText
android:background="@android:color/holo_green_dark"
android:text="hahah"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_width="200dp"
android:layout_height="100dp"/>
<EditText
android:background="@android:color/holo_blue_dark"
android:text="hahah"
android:layout_width="@dimen/dp250"
android:layout_height="100dp"/>
</com.jhzl.customview.MineLineLayout>
横向布局的测量
private void measureHorizontal(int widthMeasureSpec, int heightMeasureSpec) {
int totalHeight = 0;
int totalWidth = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
//计算最大高度
totalHeight = Math.max(totalHeight,child.getMeasuredHeight());
MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
//计算总宽度
totalWidth = totalWidth + ((MarginLayoutParams) layoutParams).leftMargin+child.getMeasuredWidth();
}
Log.d(TAG,"totalWidth = "+totalWidth+" totalHeight = "+totalHeight);
setMeasuredDimension(totalWidth, totalHeight);
}
测量完了之后,就是我们熟悉的layout环节了:
private void horizontalLayout() {
int curLeft = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
VerticalLayoutParams layoutParams = (VerticalLayoutParams) child.getLayoutParams();
curLeft = curLeft + layoutParams.leftMargin;
child.layout(curLeft, 0, curLeft+child.getMeasuredWidth(), child.getMeasuredHeight());
curLeft = curLeft + child.getMeasuredWidth();
}
}
接下来就是我们熟悉的试验结果观察环节了: