1,实现效果
2,实现逻辑
【1】继承 ViewGroup重写CrossLayout构构造方法,系统会默认的添加onLayout方法
public class CrossLayout extends ViewGroup {
public CrossLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
//要对孩子进行排版
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
【2】MainActivity 布局使用
<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=".MainActivity" >
<com.xiaoshuai.crosslayout.CrossLayout
android:id="@+id/cl"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<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="#ff00aa" />
<View
android:layout_width="200dp"
android:layout_height="50dp"
android:background="#000000" />
</com.xiaoshuai.crosslayout.CrossLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="revert"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="click" />
</RelativeLayout>
【3】创建onMeasure 方法
-
measureChildren(0, 0); 0,0 是默认模式测量孩子布局
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//需要测量viewgroup里面的孩子
measureChildren(0, 0);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
【4】onLayout对布局进行排版
-
左右摆放,
//要对孩子进行排版
@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 childAt = getChildAt(i);
//对孩子进行排版
int left = 0;
if(isStartLeft){
if (i % 2 == 0) {
//摆在左边
left = 0;
}else {
//摆在右边
left = getMeasuredWidth() - childAt.getMeasuredWidth();
}
}else {
if (i % 2 == 0) {
//摆在左边
left = getMeasuredWidth() - childAt.getMeasuredWidth();
}else {
//摆在右边
left = 0;
}
}
int right = left+childAt.getMeasuredWidth();
int bottom = top + childAt.getMeasuredHeight();
childAt.layout(left, top, right, bottom);
//动态改变top的值
top+=childAt.getMeasuredHeight();
}
}
【5】MainActivity中设置点击事件
//点击按钮动态切换view
public void click(View v) {
cl.updateLayout();
}
}
【6】CrossLayout中动态更改布局
-
requestLayout(); //请求重新布局
//动态切换view
public void updateLayout() {
isStartLeft = !isStartLeft;
requestLayout(); //请求重新布局
}