1.自定义类继承ViewGroup,必须定义构造函数、定制控件位置函数(onLayout())、测量函数(onMeasure())。
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int mViewGroupWidth = getMeasuredWidth(); //当前ViewGroup的总宽度
int mPainterPosX = left; //当前绘图光标横坐标位置
int mPainterPosY = top; //当前绘图光标纵坐标位置
int childCount = getChildCount();
for ( int i = 0; i < childCount; i++ ) {
View childView = getChildAt(i);
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
//如果剩余的空间不够,则移到下一行开始位置
if( mPainterPosX + width > mViewGroupWidth ) {
mPainterPosX = left;
mPainterPosY += height;
}
//执行ChildView的绘制
childView.layout(mPainterPosX,mPainterPosY,mPainterPosX+width, mPainterPosY+height);
//记录当前已经绘制到的横坐标位置
mPainterPosX += width;
}
}xml中:<com.titcktick.customview.CustomViewGroup 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">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/>
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/>
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/>
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/>
</com.titcktick.customview.CustomViewGroup>
本文介绍如何通过自定义ViewGroup实现水平排列子视图并自动换行的效果。具体包括自定义ViewGroup的构造函数定义、onLayout方法实现,以及如何在XML文件中使用自定义的ViewGroup。
2676

被折叠的 条评论
为什么被折叠?



