美文网首页
Android进阶之自定义View实战(六)流式布局FlowLa

Android进阶之自定义View实战(六)流式布局FlowLa

作者: kakaxicm | 来源:发表于2018-05-02 16:49 被阅读0次

引言

前面我们讲到自定义View的测量和布局原理,本文基于这两个知识点,定义一个经常用到的静态ViewGroup案例--流式布局。在我之前的商业项目艺术签名专业版(打个小广告哈)中,布局应用效果如下:

流式布局效果

实现思路

1.测量部分。
遍历测量子View,得到大小后,按行处理:换行前,每一行的宽linewidth为子View的宽累加,每一行高lineheight为该行子View的最大值;换行后重新计算行宽和行高,最终的测量结果:宽取行宽的最大值,高为行高的累加值
2.布局部分。
以行为单位布局,而行高必须得得到一整行得到,所以需要保存每一行的行高和每一行的View集合(或者改行子View的布局参数Rect,这里为了逻辑更清晰,将逻辑分行和实际布局分开,采用View集合)。

1.onMeasure实现

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //Step1:拿到父View期望的大小
        int resultWidth = 0;
        int resultHeight = 0;
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        //最终的测量结果
        resultWidth = 0;
        resultHeight = 0;

        //step2:自己定义View的逻辑,根据子View大小确定父View大小
        //每一行的宽度,View的宽度取最大宽度resultWidth
        int lineWidth = 0;
        //每一行的高度,累加得到resultHeight
        int lineHeight = 0;

        int count = getChildCount();
        //遍历子View,测量子View,计算宽高
        for (int i = 0; i < count; i++) {
            //Step1 获得每个Child的宽高和Margin,得出每个child占据的空间
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            Log.e("Flow", "onMeasure:" + i + ":" + child.getMeasuredWidth());
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            //child占据空间
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;//注意,测量后,布局之前,只能取getMeasuredHeight,不能取getHeight

            //Step2.按行处理,注意这里的换行条件:判断剩下的空间是否容得下这个child,考虑padding
            if (lineWidth + childWidth < widthSize - getPaddingLeft() - getPaddingRight()) {//未换行,宽度累加,每行的高度取child的最大值
                lineWidth = lineWidth + childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            } else {//换行,宽度取行宽度的最大值,高度累加
                resultWidth = Math.max(lineWidth, childWidth);
                resultHeight = resultHeight + lineHeight;

                lineWidth = childWidth;//行宽高重新开始计算
                lineHeight = childHeight;
            }

            //到最后一个,需要最后一行的宽高处理下,exp:两次换行,实际是3行
            if (i == count - 1) {
                resultWidth = Math.max(lineWidth, resultWidth);//宽度是行宽的最大值
                resultHeight = resultHeight + lineHeight;//最后一行加上去
            }

        }
        //如果是精确模式,则采用父布局指定的尺寸
        if (modeWidth == MeasureSpec.EXACTLY) {
            resultWidth = widthSize;
        }else{//wrap_content
            //到这里resultWidth为子View区域所占的宽度
            resultWidth += getPaddingLeft() + getPaddingRight();
        }
        if (modeHeight == MeasureSpec.EXACTLY) {
            resultHeight = heightSize;
        }else{//wrap_content
            //到这里resultHeight为子View区域所占的高度
            resultHeight += getPaddingBottom() + getPaddingTop();
        }
        setMeasuredDimension(resultWidth, resultHeight);
    }

这里容易出错的地方:
(1)换行逻辑:if(lineWidth + childWidth < widthSize - getPaddingLeft() - getPaddingRight())表示本行剩余的空间能装下当前的子View,所以不需要需要换行;否则重开一行继续计算;
(2)最后一行的行宽和行高纳入计算,因为换行次数比行数多一,不要遗漏;
(3)最后的宽高不要忘记考虑padding。

2.onLayout实现

   /**
     * 流式布局的布局要素:
     * 以行为单位布局,而行高必须得遍历完一整行才能得到,
     * 所以需要保存每一行的行高和每一行的View(或者布局参数,
     * 这里为了逻辑更清晰,每一行保存View)
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllViews.clear();
        mLineHeights.clear();
        int parentWidth = getMeasuredWidth();
        int lineWidth = 0;
        int lineHeight = 0;

        int count = getChildCount();
        // 存储每一行所有的childView
        List<View> lineViews = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            Log.e("Flow", "onLayout:" + child.getMeasuredWidth());
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
            if (lineWidth + childWidth > parentWidth - getPaddingLeft() - getPaddingRight()) {
                //TODO 换行
                mAllViews.add(lineViews);//保存本行的View
                mLineHeights.add(lineHeight);//保存本行行高
                //新开辟一行
                lineViews = new ArrayList<>();
                lineWidth = 0;
                lineHeight = 0;
            }

            //一行中进行累加操作
            lineWidth += childWidth;
            lineHeight = Math.max(lineHeight, childHeight);
            lineViews.add(child);
        }

        //别忘了最后一行需要加入计算
        mAllViews.add(lineViews);
        mLineHeights.add(lineHeight);

        //有了每一行View和行高,下面进行布局
        /**
         * 布局的起点,别忘了起点参考系是相对于父布局的左上角的,所以布局起点位置为paddingLeft和paddingRight
         */
        int left = getPaddingLeft();
        int top = getPaddingTop();
        //按行布局
        int lineNumbers = mAllViews.size();
        for (int i = 0; i < lineNumbers; i++) {
            lineViews = mAllViews.get(i);
            lineHeight = mLineHeights.get(i);
            //布局每一行
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc = lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                child.layout(lc, tc, rc, bc);
                //下一个
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }

            //下一行开始布局
            left = getPaddingLeft();
            top += lineHeight;
        }
    }

需要注意以下几点:
1.布局起点问题,这里的left和right都是相对父布局的左上角而言的,所以需要考虑padding;
2.分行部分的代码逻辑和onMeasure很相似,做好集合处理即可;
常量及覆写addView方法:

    private final int DIP_ITEM_GAP = 5;
    private int topGap = (int) SizeUtils.dp2Px(getResources(), DIP_ITEM_GAP);
    private int leftGap = (int) SizeUtils.dp2Px(getResources(), DIP_ITEM_GAP);
    private int bottomGap = (int) SizeUtils.dp2Px(getResources(), DIP_ITEM_GAP);
    private int rightGap = (int) SizeUtils.dp2Px(getResources(), DIP_ITEM_GAP);
    @Override
    public void addView(View child) {
        MarginLayoutParams lp = new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT, MarginLayoutParams.WRAP_CONTENT);
        lp.bottomMargin = bottomGap;
        lp.topMargin = topGap;
        lp.leftMargin = leftGap;
        lp.rightMargin = rightGap;
        child.setBackgroundResource(R.drawable.bg_button_gray);
        super.addView(child, lp);
    }

以上就是FlowLayout的代码,通过本文的学习,希望读者可以知道基本的ViewGroup的实现套路:
1.onMeasure方法拿到子View的宽高,考虑padding,随便浪去吧!
2.onLayout方法处理好子View的布局位置,随便浪去吧!
这里的FlowLayout案例是静态ViewGroup,没有考虑手势及滑动处理问题,想要实现动态交互功能的View/ViewGroup,就需要学习View的触摸事件分发和滚动机制,后面会详细分析这两块。

相关文章

网友评论

      本文标题:Android进阶之自定义View实战(六)流式布局FlowLa

      本文链接:https://www.haomeiwen.com/subject/szjcrftx.html