工作日記第五篇(自定義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è)置子控件的測(cè)量模式和大小 根據(jù)所有子控件設(shè)置自己的寬和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 獲得它的父容器為它設(shè)置的測(cè)量模式和大小
        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);
            // 測(cè)量每一個(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è)方法是用于測(cè)量該控件以及子控件的大小等屬性凳寺。widthMeasureSpec鸭津、heightMeasureSpec分別包括了寬和高的size和mode。
1肠缨、size:通過MeasureSpec.getSize(widthMeasureSpec)可以獲取系統(tǒng)測(cè)量后建議寬度逆趋,高度同理。
2晒奕、 mode:通過MeasureSpec.getMode(widthMeasureSpec)可以獲取系統(tǒng)測(cè)量時(shí)的測(cè)量模式分別為AT_MOST闻书、EXACTLY、UNSPECIFIED脑慧。AT_MOST:當(dāng)子控件屬性設(shè)置為wrap_content時(shí)所使用的測(cè)量模式魄眉。EXACTLY:當(dāng)子控件屬性指明數(shù)值時(shí)使用的測(cè)量模式<如70dp>。

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

setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : height);
  onLayout就比較好理解了闷袒,根據(jù)測(cè)量出來的數(shù)據(jù)坑律,將子控件按照要求排放當(dāng)相應(yīng)的位置即可
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市囊骤,隨后出現(xiàn)的幾起案子晃择,更是在濱河造成了極大的恐慌,老刑警劉巖也物,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宫屠,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡滑蚯,警方通過查閱死者的電腦和手機(jī)浪蹂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來告材,“玉大人坤次,你說我怎么就攤上這事〈雌希” “怎么了浙踢?”我有些...
    開封第一講書人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)灿渴。 經(jīng)常有香客問我洛波,道長(zhǎng),這世上最難降的妖魔是什么骚露? 我笑而不...
    開封第一講書人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任蹬挤,我火速辦了婚禮,結(jié)果婚禮上棘幸,老公的妹妹穿的比我還像新娘焰扳。我一直安慰自己,他們只是感情好误续,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開白布吨悍。 她就那樣靜靜地躺著,像睡著了一般蹋嵌。 火紅的嫁衣襯著肌膚如雪育瓜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,156評(píng)論 1 308
  • 那天栽烂,我揣著相機(jī)與錄音躏仇,去河邊找鬼。 笑死腺办,一個(gè)胖子當(dāng)著我的面吹牛焰手,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播怀喉,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼书妻,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了躬拢?” 一聲冷哼從身側(cè)響起躲履,我...
    開封第一講書人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎估灿,沒想到半個(gè)月后崇呵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡馅袁,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年域慷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片汗销。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡犹褒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出弛针,到底是詐尸還是另有隱情叠骑,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布削茁,位于F島的核電站宙枷,受9級(jí)特大地震影響掉房,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜慰丛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一卓囚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧诅病,春花似錦哪亿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至芥永,卻和暖如春篡殷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背恤左。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工贴唇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人飞袋。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓戳气,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親巧鸭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瓶您,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容