Android進(jìn)階之自定義View實(shí)戰(zhàn)(六)流式布局FlowLayout實(shí)現(xiàn)

引言

前面我們講到自定義View的測(cè)量和布局原理,本文基于這兩個(gè)知識(shí)點(diǎn),定義一個(gè)經(jīng)常用到的靜態(tài)ViewGroup案例--流式布局。在我之前的商業(yè)項(xiàng)目藝術(shù)簽名專業(yè)版(打個(gè)小廣告哈)中,布局應(yīng)用效果如下:

流式布局效果

實(shí)現(xiàn)思路

1.測(cè)量部分。
遍歷測(cè)量子View,得到大小后,按行處理:換行前,每一行的寬linewidth為子View的寬累加,每一行高lineheight為該行子View的最大值;換行后重新計(jì)算行寬和行高,最終的測(cè)量結(jié)果:寬取行寬的最大值,高為行高的累加值
2.布局部分。
以行為單位布局,而行高必須得得到一整行得到,所以需要保存每一行的行高和每一行的View集合(或者改行子View的布局參數(shù)Rect,這里為了邏輯更清晰,將邏輯分行和實(shí)際布局分開,采用View集合)。

1.onMeasure實(shí)現(xiàn)

    @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);
        //最終的測(cè)量結(jié)果
        resultWidth = 0;
        resultHeight = 0;

        //step2:自己定義View的邏輯,根據(jù)子View大小確定父View大小
        //每一行的寬度,View的寬度取最大寬度resultWidth
        int lineWidth = 0;
        //每一行的高度,累加得到resultHeight
        int lineHeight = 0;

        int count = getChildCount();
        //遍歷子View,測(cè)量子View,計(jì)算寬高
        for (int i = 0; i < count; i++) {
            //Step1 獲得每個(gè)Child的寬高和Margin,得出每個(gè)child占據(jù)的空間
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            Log.e("Flow", "onMeasure:" + i + ":" + child.getMeasuredWidth());
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            //child占據(jù)空間
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;//注意,測(cè)量后,布局之前,只能取getMeasuredHeight,不能取getHeight

            //Step2.按行處理,注意這里的換行條件:判斷剩下的空間是否容得下這個(gè)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;//行寬高重新開始計(jì)算
                lineHeight = childHeight;
            }

            //到最后一個(gè),需要最后一行的寬高處理下,exp:兩次換行,實(shí)際是3行
            if (i == count - 1) {
                resultWidth = Math.max(lineWidth, resultWidth);//寬度是行寬的最大值
                resultHeight = resultHeight + lineHeight;//最后一行加上去
            }

        }
        //如果是精確模式,則采用父布局指定的尺寸
        if (modeWidth == MeasureSpec.EXACTLY) {
            resultWidth = widthSize;
        }else{//wrap_content
            //到這里resultWidth為子View區(qū)域所占的寬度
            resultWidth += getPaddingLeft() + getPaddingRight();
        }
        if (modeHeight == MeasureSpec.EXACTLY) {
            resultHeight = heightSize;
        }else{//wrap_content
            //到這里resultHeight為子View區(qū)域所占的高度
            resultHeight += getPaddingBottom() + getPaddingTop();
        }
        setMeasuredDimension(resultWidth, resultHeight);
    }

這里容易出錯(cuò)的地方:
(1)換行邏輯:if(lineWidth + childWidth < widthSize - getPaddingLeft() - getPaddingRight())表示本行剩余的空間能裝下當(dāng)前的子View,所以不需要需要換行;否則重開一行繼續(xù)計(jì)算;
(2)最后一行的行寬和行高納入計(jì)算,因?yàn)閾Q行次數(shù)比行數(shù)多一,不要遺漏;
(3)最后的寬高不要忘記考慮padding。

2.onLayout實(shí)現(xiàn)

   /**
     * 流式布局的布局要素:
     * 以行為單位布局,而行高必須得遍歷完一整行才能得到,
     * 所以需要保存每一行的行高和每一行的View(或者布局參數(shù),
     * 這里為了邏輯更清晰,每一行保存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();
        // 存儲(chǔ)每一行所有的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;
            }

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

        //別忘了最后一行需要加入計(jì)算
        mAllViews.add(lineViews);
        mLineHeights.add(lineHeight);

        //有了每一行View和行高,下面進(jìn)行布局
        /**
         * 布局的起點(diǎn),別忘了起點(diǎn)參考系是相對(duì)于父布局的左上角的,所以布局起點(diǎn)位置為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);
                //下一個(gè)
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }

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

需要注意以下幾點(diǎn):
1.布局起點(diǎn)問題,這里的left和right都是相對(duì)父布局的左上角而言的,所以需要考慮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的代碼,通過本文的學(xué)習(xí),希望讀者可以知道基本的ViewGroup的實(shí)現(xiàn)套路:
1.onMeasure方法拿到子View的寬高,考慮padding,隨便浪去吧!
2.onLayout方法處理好子View的布局位置,隨便浪去吧!
這里的FlowLayout案例是靜態(tài)ViewGroup,沒有考慮手勢(shì)及滑動(dòng)處理問題,想要實(shí)現(xiàn)動(dòng)態(tài)交互功能的View/ViewGroup,就需要學(xué)習(xí)View的觸摸事件分發(fā)和滾動(dòng)機(jī)制,后面會(huì)詳細(xì)分析這兩塊。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容