class FlowLayout extends ViewGroup {
private float itemHeight;
private float itemSpace;
private float dividerHeight;
public FlowLayout(Context context) {
super( context );
}
public FlowLayout(Context context, AttributeSet attrs) {
super( context, attrs );
}
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super( context, attrs, defStyleAttr );
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren( widthMeasureSpec,heightMeasureSpec );
int widthSize = MeasureSpec.getSize( widthMeasureSpec );
int heightSize = MeasureSpec.getSize( heightMeasureSpec );
int modeWidth = MeasureSpec.getMode( widthMeasureSpec );
int modeHeight = MeasureSpec.getMode( heightMeasureSpec );
int resultWidth=0;
int resultHeight=0;
Map<String,Integer> computeResult = compute(widthSize-getPaddingRight());
if(modeWidth == MeasureSpec.EXACTLY){
resultWidth = widthSize;
}else{
resultWidth = computeResult.get( "allChildWidth" );
}
if(modeHeight == MeasureSpec.EXACTLY){
resultHeight = heightSize;
}else{
resultHeight = computeResult.get( "allChildHeight" );
}
setMeasuredDimension( resultWidth,resultHeight );
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int count = getChildCount();
for(int i= 0;i<count;i++){
View child=getChildAt( i );
Rect rect = (Rect) child.getTag();
child.layout( rect.left,rect.top,rect.right,rect.bottom );
}
}
private Map<String,Integer> compute(int flowWidth){
boolean aRow = true;
MarginLayoutParams params;
int lineWidth = getPaddingLeft();
int lineHeight = getPaddingTop();
int rowMaxHeight = 0;
int count =getChildCount();
for(int i=0;i<count;i++){
View child = getChildAt( i );
params =(MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth() + params.rightMargin + params.leftMargin;
int childHeight = child.getMeasuredHeight() + params.topMargin + params.bottomMargin;
rowMaxHeight = Math.max(rowMaxHeight,childHeight);
if(lineWidth + childWidth > flowWidth ){
lineHeight += rowMaxHeight;
rowMaxHeight = childHeight;
aRow = false;
lineWidth = getPaddingLeft();
}
lineWidth += childWidth;
child.setTag( new Rect( lineWidth - childWidth + params.leftMargin,lineHeight +
params.topMargin,lineWidth - params.rightMargin,lineHeight + childHeight - params.bottomMargin ) );
}
Map<String,Integer> flowMap = new HashMap<>( );
if (aRow) {
flowMap.put( "allChildWidth",lineWidth + getPaddingRight() );
} else {
flowMap.put( "allChildWidth",flowWidth + getPaddingRight() );
}
flowMap.put( "allChildHeight",lineHeight + rowMaxHeight+getPaddingBottom() );
return flowMap;
}
}