Android View

ViewRoot & DecorView

  • ViewRoot --> ViewRootImpl 連接 WindowManager 和 DecorView漱挚,通過(guò) ViewRoot 完成 View 的三大流程汽煮。
  • View 的繪制流程從 ViewRoot 的 performTraversals 方法開(kāi)始
performTraversals的工作流程.png
  • DecorView --> 頂級(jí) View拱燃,一般包含一個(gè)豎直方向的 LinearLayout,其中有標(biāo)題欄和內(nèi)容欄。
Android UI 界面架構(gòu)圖.png

MesaureSpec

  • MeasureSpec = SpecMode(測(cè)量模式) + SpecSize(規(guī)格大小);
public static class MeasureSpec {
        private static final int MODE_SHIFT = 30;
        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

        /**
         * 要多大給多大宋梧,用于系統(tǒng)內(nèi)部
         */
        public static final int UNSPECIFIED = 0 << MODE_SHIFT;

        /**
         * 精確大小 包含 match_parent 和 具體數(shù)值
         */
        public static final int EXACTLY = 1 << MODE_SHIFT;

        /**
         * 對(duì)應(yīng) wrap_content, 不能大于父容器指定的大小
         */
        public static final int AT_MOST = 2 << MODE_SHIFT;

        public static int makeMeasureSpec(int size, int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }

        public static int getMode(int measureSpec) {
            return (measureSpec & MODE_MASK);
        }

        public static int getSize(int measureSpec) {
            return (measureSpec & ~MODE_MASK);
        }
    }
  • MeasureSpec 和 LayoutParams 的對(duì)應(yīng)關(guān)系

View 的工作流程

  • measure 過(guò)程
/**
     * <p>
     * This is called to find out how big a view should be. The parent
     * supplies constraint information in the width and height parameters.
     * </p>
     *
     * <p>
     * The actual measurement work of a view is performed in
     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
     * </p>
     *
     *
     * @param widthMeasureSpec Horizontal space requirements as imposed by the
     *        parent
     * @param heightMeasureSpec Vertical space requirements as imposed by the
     *        parent
     *
     * @see #onMeasure(int, int)
     */
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
'''
onMeasure(widthMeasureSpec, heightMeasureSpec);
'''
}

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/**
*This method must be called by {@link #onMeasure(int, int)} to store the measured width and measured height.
*/      
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
 }


 public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }
  • ViewGroup 的 measure 過(guò)程
/**
     * Ask all of the children of this view to measure themselves, taking into
     * account both the MeasureSpec requirements for this view and its padding.
     * We skip children that are in the GONE state The heavy lifting is done in
     * getChildMeasureSpec.
     *
     * @param widthMeasureSpec The width requirements for this view
     * @param heightMeasureSpec The height requirements for this view
     */
    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

/**
     * Ask one of the children of this view to measure itself, taking into
     * account both the MeasureSpec requirements for this view and its padding.
     * The heavy lifting is done in getChildMeasureSpec.
     *
     * @param child The child to measure
     * @param parentWidthMeasureSpec The width requirements for this view
     * @param parentHeightMeasureSpec The height requirements for this view
     */
    protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
  • 在 Activity 啟動(dòng)的時(shí)候獲取某個(gè) View 的寬/高
    View 的 measure 過(guò)程和 Activity 的生命周期方法不是同步執(zhí)行的,無(wú)法保證 Activity 執(zhí)行了 onCreate狰挡、onResume 時(shí)某個(gè) View 已經(jīng)測(cè)量完畢捂龄,如果沒(méi)有測(cè)量完,獲得的寬/高就是0.
    1) onWindowFocusChanged --> 得到和失去焦點(diǎn)時(shí)調(diào)用(例如加叁,Activity 繼續(xù)執(zhí)行和暫停執(zhí)行)
public void onWindowFocusChanged(boolean hasFocus){
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus){
        int width = view.getMeasuredWidth();
        int height = view.getMeasureHeight();
    }
}
  1. view.post(runnable)
    通過(guò) post 可以將一個(gè) runnable 投遞到消息隊(duì)列的尾部跺讯,然后等待 Looper調(diào)用此 runnable 的時(shí)候,View也已經(jīng)初始化好了
protected void onStart(){
    super.onStart();
    view.post(new Runnable(){
        @Override
        public void run(){
            int width = view.getMeasureWidth();
            int height = view.getMeasureHeight();
        }
    });
}
  1. ViewTreeObserver
    使用 ViewTreeObserver 的onGlobalLayoutListener接口殉农,當(dāng) View 樹(shù)的狀態(tài)發(fā)生改變或者 View 樹(shù)內(nèi)部的 View 的可見(jiàn)性發(fā)生改變時(shí),該接口被調(diào)用局荚。
protected void onStart(){
    super.onStart();

    ViewTreeOnserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override
        public void onGlobalLayout(){
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        int width = view.getMeasureWidth();
        int height = view.getMeasureHeight();
        }
    })
}
  • layout 過(guò)程
    /**
     * Assign a size and position to a view and all of its
     * descendants
     *
public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = 0; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }


    /**
     * Called from layout when this view should
     * assign a size and position to each of its children.
     */
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }

  • draw 過(guò)程
    1)繪制背景 background.draw
  1. 繪制自己 onDraw
    3)繪制 children dispatchDraw
    4)繪制裝飾 onDrawScrollBars
public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background
         *      2. If necessary, save the canvas' layers to prepare for fading
         *      3. Draw view's content
         *      4. Draw children
         *      5. If necessary, draw the fading edges and restore layers
         *      6. Draw decorations (scrollbars for instance)
         */

        // Step 1, draw the background, if needed
        int saveCount;

        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // we're done...
            return;
        }
'''
}

自定義 View

  1. CircleView ---繼承 View 重寫(xiě) onDraw 方法
    Demo 地址
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末超凳,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子耀态,更是在濱河造成了極大的恐慌轮傍,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件首装,死亡現(xiàn)場(chǎng)離奇詭異创夜,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)仙逻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門驰吓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人系奉,你說(shuō)我怎么就攤上這事檬贰。” “怎么了缺亮?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵翁涤,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng)葵礼,這世上最難降的妖魔是什么号阿? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮鸳粉,結(jié)果婚禮上扔涧,老公的妹妹穿的比我還像新娘。我一直安慰自己赁严,他們只是感情好扰柠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著疼约,像睡著了一般卤档。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上程剥,一...
    開(kāi)封第一講書(shū)人閱讀 51,182評(píng)論 1 299
  • 那天劝枣,我揣著相機(jī)與錄音,去河邊找鬼织鲸。 笑死舔腾,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的搂擦。 我是一名探鬼主播稳诚,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼瀑踢!你這毒婦竟也來(lái)了扳还?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤橱夭,失蹤者是張志新(化名)和其女友劉穎氨距,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體棘劣,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡俏让,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了茬暇。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片首昔。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖糙俗,靈堂內(nèi)的尸體忽然破棺而出沙廉,到底是詐尸還是另有隱情,我是刑警寧澤臼节,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布撬陵,位于F島的核電站珊皿,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏巨税。R本人自食惡果不足惜蟋定,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望草添。 院中可真熱鬧驶兜,春花似錦、人聲如沸远寸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)驰后。三九已至肆资,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間灶芝,已是汗流浹背郑原。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留夜涕,地道東北人犯犁。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像女器,于是被迫代替她去往敵國(guó)和親酸役。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

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