AutoGridLayout(自动滑动GridLayout)

package autochangelineview.app.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
* Created by gong sheng on 2016/12/27
*/
public class FixFlowLayout extends ViewGroup {
public FixFlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

int mColumnCount = 4;

public List<View> getShowView() {
List<View> list = new ArrayList<View>();
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
if (getChildAt(i).getVisibility() == VISIBLE) {
list.add(getChildAt(i));
}
}
return list;
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
List<View> showView = getShowView();
int childCount = showView.size();
//光标
int top = getPaddingTop();
int left = getPaddingLeft();
for (int i = 0; i < childCount; i++) {
View view = showView.get(i);
//排列
view.layout(left, top, left + view.getMeasuredWidth(), top + view.getMeasuredHeight());
if (i == 0) {
left += view.getMeasuredWidth();
} else if (i % mColumnCount == 0) {
left += view.getMeasuredWidth();
} else if (mColumnCount - i % mColumnCount == 1) {
left = getPaddingLeft();
top += view.getMeasuredHeight();
} else {
left += view.getMeasuredWidth();
}
}
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
//高度测量模式
int childHeightMeasureSpec = 0;
//宽度测量模式
int childWidthMeasureSpec = 0;
//测量子view并重新赋值
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
measureChild(childView, widthMeasureSpec, heightMeasureSpec);
childHeightMeasureSpec =
MeasureSpec.makeMeasureSpec(childView.getMeasuredHeight(), MeasureSpec.AT_MOST);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childView.getMeasuredWidth(), MeasureSpec.EXACTLY);
childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}

@Override
public void addView(View child, LayoutParams params) {
super.addView(child, params);
}
}
原文地址:https://www.cnblogs.com/g-sheng/p/6227932.html