效果图,点击按钮,左右两边互相换位置
一对于viewGoup的测量来说,需要测量每一个孩子的大小..在调用super方法的基础上,可以直接调用measureChildren方法.或者一个个的测量
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// measureChildren(widthMeasureSpec,heightMeasureSpec);
//viewGroup的测量需要测量每一个孩子的大小,可用用measureChildren方法来实现
int count = getChildCount();
for (int i = 0; i <count ; i++) {
View childAt = getChildAt(i);
measureChild(childAt,widthMeasureSpec,heightMeasureSpec);
}
}
二.对于viewgroup的layout.同样得到孩子的个数,分别计算每一个孩子相对于屏幕左,上,右,下的坐标.调用layout方法.来实现.
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int top = 0;
//关于布局,拿到每一个孩子对象,分别计算每一个孩子相对与屏幕的坐标.
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int left = 0;
if (isStartLeft) {
if (i % 2 == 0) {
//孩子摆左边
left = 0;
} else {
//孩子摆右边
left = getMeasuredWidth() - child.getMeasuredWidth();
}
} else {
if (i % 2 == 0) {
//孩子摆右边
left = getMeasuredWidth() - child.getMeasuredWidth();
} else {
//i是奇数
//孩子摆左边
left = 0;
}
}
//得到第一个孩子的坐标
int right = left + child.getMeasuredWidth();
int bottom = top + child.getMeasuredHeight();
child.layout(left, top, right, bottom);
//更新top值,布局下一个孩子
top += child.getMeasuredHeight();
}
}
三,对外提供一个方法,改变布局..需要调用requestLayout方法重新布局.另外invalidate方法是重新绘制
/**
* 交叉布局
*/
private boolean isStartLeft = false;
public void revert() {
//变换标记
isStartLeft = !isStartLeft;
// invalidate();//触发重新绘制 onDraw
requestLayout();//请求重新布局 onLayout
}
}
主页面的布局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.viewgrouplayout.MainActivity">
<com.example.viewgrouplayout.MyViewGroup
android:id="@+id/viewGoup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<View
android:layout_width="200dp"
android:layout_height="50dp"
android:background="#ff0000" />
<View
android:layout_width="200dp"
android:layout_height="50dp"
android:background="#00ff00" />
<View
android:layout_width="200dp"
android:layout_height="50dp"
android:background="#0000ff" />
<View
android:layout_width="200dp"
android:layout_height="50dp"
android:background="#000000" />
</com.example.viewgrouplayout.MyViewGroup>
<Button
android:text="revert"
android:onClick="go"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>