首页 > 代码库 > AutoGridLayout(自动滑动GridLayout)

AutoGridLayout(自动滑动GridLayout)

package autochangelineview.app.view;

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

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

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

    int mColumnCount = 2;

    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 = 0;
        int left = 0;
        for (int i = 0; i < childCount; i++) {
            View view = showView.get(i);
            if (i == 0) {
            } else if (i % mColumnCount == 0) {
                left = 0;
                top += view.getMeasuredHeight();
            } else {
                left += view.getMeasuredWidth();
            }
            //排列
            view.layout(left, top, left + view.getMeasuredWidth(), top + view.getMeasuredHeight());
            Log.e("gongsheng1", i + ":" + left + "," + top);
        }
    }


    @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(getMeasuredWidth() / mColumnCount, MeasureSpec.EXACTLY);
            childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            Log.e("gongsheng2", i + ":" + childWidthMeasureSpec + "," + childHeightMeasureSpec);
        }
    }
}

 

AutoGridLayout(自动滑动GridLayout)