工作日記第五篇(自定義View<onMeasure和onLayout的理解>)

首先聲明下面的代碼是從http://blog.csdn.net/lmj623565791/article/details/38352503摘取,個(gè)人認(rèn)為這段代碼對(duì)于理解自定義View有很大的幫助。

package com.zhy.zhy_flowlayout02;

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

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

public class FlowLayout extends ViewGroup
{

    private static final String TAG = "FlowLayout";


    public FlowLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(
            ViewGroup.LayoutParams p)
    {
        return new MarginLayoutParams(p);
    }

    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
    {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected ViewGroup.LayoutParams generateDefaultLayoutParams()
    {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    /**
     * 負(fù)責(zé)設(shè)置子控件的測量模式和大小 根據(jù)所有子控件設(shè)置自己的寬和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 獲得它的父容器為它設(shè)置的測量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        Log.e(TAG, sizeWidth + "," + sizeHeight);

        // 如果是warp_content情況下,記錄寬和高
        int width = 0;
        int height = 0;
        /**
         * 記錄每一行的寬度,width不斷取最大寬度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度,累加至height
         */
        int lineHeight = 0;

        int cCount = getChildCount();

        // 遍歷每個(gè)子元素
        for (int i = 0; i < cCount; i++)
        {
            View child = getChildAt(i);
            // 測量每一個(gè)child的寬和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            // 當(dāng)前子空間實(shí)際占據(jù)的寬度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            // 當(dāng)前子空間實(shí)際占據(jù)的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;
            /**
             * 如果加入當(dāng)前child,則超出最大寬度,則的到目前最大寬度給width,類加height 然后開啟新行
             */
            if (lineWidth + childWidth > sizeWidth)
            {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新開啟新行,開始記錄
                // 疊加當(dāng)前高度,
                height += lineHeight;
                // 開啟記錄下一行的高度
                lineHeight = childHeight;
            } else
            // 否則累加值lineWidth,lineHeight取最大高度
            {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 如果是最后一個(gè),則將當(dāng)前記錄的最大寬度和當(dāng)前l(fā)ineWidth做比較
            if (i == cCount - 1)
            {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }

        }
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : height);

    }
    /**
     * 存儲(chǔ)所有的View,按行記錄
     */
    private List<List<View>> mAllViews = new ArrayList<List<View>>();
    /**
     * 記錄每一行的最大高度
     */
    private List<Integer> mLineHeight = new ArrayList<Integer>();
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        mAllViews.clear();
        mLineHeight.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 存儲(chǔ)每一行所有的childView
        List<View> lineViews = new ArrayList<View>();
        int cCount = getChildCount();
        // 遍歷所有的孩子
        for (int i = 0; i < cCount; i++)
        {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果已經(jīng)需要換行
            if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width)
            {
                // 記錄這一行所有的View以及最大高度
                mLineHeight.add(lineHeight);
                // 將當(dāng)前行的childView保存,然后開啟新的ArrayList保存下一行的childView
                mAllViews.add(lineViews);
                lineWidth = 0;// 重置行寬
                lineViews = new ArrayList<View>();
            }
            /**
             * 如果不需要換行,則累加
             */
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);
        }
        // 記錄最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        int left = 0;
        int top = 0;
        // 得到總行數(shù)
        int lineNums = mAllViews.size();
        for (int i = 0; i < lineNums; i++)
        {
            // 每一行的所有的views
            lineViews = mAllViews.get(i);
            // 當(dāng)前行的最大高度
            lineHeight = mLineHeight.get(i);

            Log.e(TAG, "第" + i + "行 :" + lineViews.size() + " , " + lineViews);
            Log.e(TAG, "第" + i + "行, :" + lineHeight);

            // 遍歷當(dāng)前行所有的View
            for (int j = 0; j < lineViews.size(); j++)
            {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE)
                {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child
                        .getLayoutParams();

                //計(jì)算childView的left,top,right,bottom
                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc =lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                Log.e(TAG, child + " , l = " + lc + " , t = " + t + " , r ="
                        + rc + " , b = " + bc);

                child.layout(lc, tc, rc, bc);
                
                left += child.getMeasuredWidth() + lp.rightMargin
                        + lp.leftMargin;
            }
            left = 0;
            top += lineHeight;
        }

    }
}

demo截圖如下:

QQ圖片20160801132634.jpg

以下是個(gè)人的理解:
首先,onMeasure(int widthMeasureSpec, int heightMeasureSpec)。這個(gè)方法是用于測量該控件以及子控件的大小等屬性。widthMeasureSpec、heightMeasureSpec分別包括了寬和高的size和mode。
1、size:通過MeasureSpec.getSize(widthMeasureSpec)可以獲取系統(tǒng)測量后建議寬度,高度同理。
2、 mode:通過MeasureSpec.getMode(widthMeasureSpec)可以獲取系統(tǒng)測量時(shí)的測量模式分別為AT_MOST、EXACTLY、UNSPECIFIED。AT_MOST:當(dāng)子控件屬性設(shè)置為wrap_content時(shí)所使用的測量模式。EXACTLY:當(dāng)子控件屬性指明數(shù)值時(shí)使用的測量模式<如70dp>。

上述代碼計(jì)算過后根據(jù)所使用的測量模式mode來判斷最后是否使用代碼計(jì)算的數(shù)值來設(shè)置該空間的大小

setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : height);
  onLayout就比較好理解了,根據(jù)測量出來的數(shù)據(jù),將子控件按照要求排放當(dāng)相應(yīng)的位置即可
最后編輯于
?著作權(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)容