Android自动换行布局

public class FlowLayout extends ViewGroup {

    /**
     * 所有子控件的容器
     */
    private List<List<View>> lineList = new ArrayList<>();

    /**
     * 每行的高度
     */
    private List<Integer> lineHeightList = new ArrayList<>();

    /**
     * 防止多次测量
     */
    private boolean measureFlag = true;

    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
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /**
     * 在被调用这个方法之前   它的父容器  已经把它的测量模式改成了当前控件的测量模式
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取到父容器 给我们的参考值
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        //获取到自己的测量模式
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        //记录当前控件里面的子控件的总高宽
        int childMaxWidth = 0;
        int childCountHeight = 0;

        //防止多次测量
        if (measureFlag) {
            measureFlag = false;
        } else {
            //当前一行,控件中的子控件的总宽度
            int lineCountWidth = 0;
            //当前一行,最高子控件的高度
            int lineMaxHeight = 0;

            //记录每个子控件的宽高
            int childWidth, childHeight;

            //创建一行空容器
            List<View> viewList = new ArrayList<>();
            int childCount = getChildCount();

            for (int i = 0; i < childCount; i++) {
                View childView = getChildAt(i);
                //先测量子控件
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                MarginLayoutParams layoutParams = (MarginLayoutParams) childView.getLayoutParams();

                //计算当前子控件的实际宽高
                childWidth = childView.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
                childHeight = childView.getMeasuredHeight() + layoutParams.topMargin + layoutParams.bottomMargin;

                //如果当前行的宽度,加上这个view的宽度,大于容器的宽度时,就换行
                if (lineCountWidth + childWidth + getPaddingLeft() + getPaddingRight() > widthSize) {
                    //需要换行的情况
                    //每次进入到这里的时候  只是保存了上一行的信息,并没有保存当前行的信息
                    //拿到所有行中,最大的宽,去决定EXACTLY时的最大宽度
                    childMaxWidth = Math.max(childMaxWidth, lineCountWidth);
                    childCountHeight += lineMaxHeight;
                    //把行高记录到集合中
                    lineHeightList.add(lineMaxHeight);
                    //把这一行的数据放进总容器
                    lineList.add(viewList);
                    //把一行的容器,重新创建一个,虽然会频繁创建,但如果调用clear,会导致lineList的栈也会被清掉
                    viewList = new ArrayList<>();
                    //把每行的高宽初始化
                    lineCountWidth = childWidth;
                    lineMaxHeight = childHeight;
                    viewList.add(childView);
                } else {
                    //不需要换行的情况
                    lineCountWidth += childWidth;
                    //取当前行的所有子控件最大的高度
                    lineMaxHeight = Math.max(lineMaxHeight, childHeight);
                    viewList.add(childView);
                }

                //这样做的原因是  之前的if else中 不会把最后一行的高度加进listLineHeight
                // 最后一行要特殊对待 不管最后一个item是不是最后一行的第一个item
                if (i == (childCount - 1)) {
                    //保存当前行信息
                    childMaxWidth = Math.max(childMaxWidth, lineCountWidth + getPaddingLeft() + getPaddingRight());
                    childCountHeight += lineMaxHeight;
                    lineHeightList.add(lineMaxHeight);
                    lineList.add(viewList);
                }
            }
        }

        //设置控件最终大小
        int measureWidth = (widthMode == MeasureSpec.EXACTLY ? widthSize : childMaxWidth + getPaddingLeft() + getPaddingRight());
        int measureHeight = (heightMode == MeasureSpec.EXACTLY ? heightSize : childCountHeight + getPaddingTop() + getPaddingBottom());
        setMeasuredDimension(measureWidth, measureHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //摆放子控件的位置
        int left, top, right, bottom;
        //保存上一个控件的边距
        int countLeft = 0;
        //保存上一行的高度的边距
        int countTop = 0;
        //遍历所有行
        for (List<View> views : lineList) {
            //遍历每一行的控件
            for (View view : views) {
                MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
                left = countLeft + layoutParams.leftMargin;
                top = countTop + layoutParams.topMargin;
                right = left + view.getMeasuredWidth();
                bottom = top + view.getMeasuredHeight();
                view.layout(left + getPaddingLeft(), top + getPaddingTop(), right + getPaddingRight(), bottom + getPaddingBottom());

                //记录当前控件的实际宽度坐标,让下一个控件知道X轴的起点在哪
                countLeft += view.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
            }

            int i = lineList.indexOf(views);
            //换行时从最左边开始
            countLeft = 0;
            //换行时累加高度
            countTop += lineHeightList.get(i);
        }
        //布局结束后清空记录的list
        lineList.clear();
        lineHeightList.clear();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,265评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,274评论 1 288
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,087评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,479评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,782评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,218评论 1 207
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,594评论 2 309
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,316评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,955评论 1 237
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,274评论 2 240
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,803评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,177评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,732评论 3 229
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,953评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,687评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,263评论 2 267
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,189评论 2 258