一. View的工做流程

不忘初心 砥礪前行, Tomorrow Is Another Day !html

相關文章

本文概要:java

  1. 概述
    • Activity的UI層次及工做流程入口
  2. 理解MeasureSpe
  3. View的工做流程
  4. 自定義View的方式及注意事項

一. 概述

如無特別說明,本次源碼版本均基於8.0.bash

1.1 Activity的UI層次

在平常開發咱們在Activity的OnCreate中經過setContentView設置自定義佈局時,實際上調用了PhoneWindow的setContentView方法,在此方法裏面首先會初始化一個DecorView.最後將咱們自定義佈局加載到DecorView佈局中id爲content的FrameLayout.app


Activity的UI結構層次圖-來自《進階之光》

爲了證明上述結論的正確性,咱們能夠參考源碼.iview

對應源碼ide

//Activity.java
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

//PhoneWindow.java
 @Override
    public void setContentView(int layoutResID) {
       
        if (mContentParent == null) {
            /**
             *  1.初始化DecorView
             */
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            /*
             *2.解析layoutResID佈局文件,將它嵌入到*mContentParent的內部
             */
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }
    
//PhoneWindow#installDecor方法
private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            //1.生成DecorView
            mDecor = generateDecor(-1);
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            //2.找到ID爲content的ViewGroup
            mContentParent = generateLayout(mDecor);

            // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
            mDecor.makeOptionalFitsSystemWindows();

            final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
                    R.id.decor_content_parent);
    //...省略部分代碼
   }         
}

複製代碼

1.2 View的工做流程入口

咱們知道ActivityThread做爲啓動入口,會經過handleLaunchActivity,建立一個Activity對象.其中在performLaunchActivity中調用OnCreate方法,也就是上一節所講內容.接着在handleResumeActivity方法裏,開始將View加載到Window最後.這裏咱們只看與View繪製相關流程.佈局

1. 首先經過WindowManager將DecorView添加到Window中,與此同時將ViewRootImpl對象經過setView將DecorView關聯起來.post

對應源碼學習

//WindowManagerImpl.java
@Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        //調用WindowManagerGlobal的addView
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }

//WindowManagerGlobal.java
    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
     
        //...省略部分代碼
        
        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {

          //...省略部分代碼

            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);

            // do this last because it fires off messages to start doing things
            try {
                //將DecorView關聯起來
                root.setView(view, wparams, panelParentView);
            } catch (RuntimeException e) {
                // BadTokenException or InvalidDisplayException, clean up.
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
                throw e;
            }
        }
    }
複製代碼

2. 在加載到Window以前,其ViewRootImpl內部會經過requestLayout方法來佈局整個DecorView樹,最終調用performTravels,依次執行DecorView的measure、layout、draw三大過程.動畫

對應源碼

//ViewRootImpl.java
 @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            //執行開始佈局
            scheduleTraversals();
        }
    }

private void performTraversals() {
//...省略部分代碼
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
//...省略部分代碼
    performLayout(lp, mWidth, mHeight);
//...省略部分代碼
    performDraw();
//...省略部分代碼
}
複製代碼

瞭解了相關啓動加載與繪製流程後,下面就開始進入正題-View相關的重要知識點.

二. 理解MeasureSpec

MeasureSpec能夠理解爲規格限制,其由specSize和specMode構成.

提供相應的打包與拆包方法: makeMeasureSpec/getMode,getSize

Mode 三種模式:

  1. EXACTLY: 精確模式
    • 父View對子view有精確的大小,大小就是specSize.
    • 對應於MACTCH_PARENT和具體數值.
  2. AT_MOST:最大模式
    • 父View對子view最大值有要求,大小就是specSize.
    • 對應於WRAP_CONTENT
  3. UNSPECIFIED

MeasureSpec 的計算方式:

  • 對於DecorView,它的MeasureSpec由窗口與自身的layoutParams共同決定---在viewRootImpl完成.

  • 對於普通View,它的MeasureSpec由父容器的MeasureSpec與自身的layoutParams共同決定---在父容器中完成.

對應源碼:

//ViewRootImpl.java
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
           
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:

            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }


//ViewGroup.java
protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        
        //對於在父元素的已佔用的空間=父元素自身padding+子元素的magrgin
        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

   /** @param 父元素的MeasureSpec
     * @param 對於在父元素的已佔用的空間=父元素自身padding+子元素的magrgin
     * @param 自身的lp參數
     * @return 子元素的MeasureSpec
     */
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);
        
        //父元素可用空間 = 父元素總的大小-已佔用的空間
        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
               
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

複製代碼

對於上述源碼咱們重點注意getChildMeasureSpec方法,其中第二個參數表明的是父元素已佔用的空間.該方法體現了生成普通View的MeasureSpec的規格.

遵循如下規則,UNSPECIFIED除外.前者表示子元素的layoutParams參數.

  • dp/px
    • EXACTLY與childSize.
  • match_parent
    • 父元素的specMode爲EXACTLY,那麼規格就是EXACTLY與parentSize.
    • 父元素的specMode爲AT_MOST,那麼規格就是AT_MOST與parentSize.
  • wrap_content
    • AT_MOST與parentSize.

從上面規則能夠發現,不管是match_parent,仍是wrap_content,最終返回的大小都是parentSize,也就是父元素的可用空間.而View在默認測量時getDefaultSize會直接返回該大小,因此在測量過程當中,須要對wrap_content進行特殊處理.具體如何處理下一篇在講解.

三. View的工做流程

measure、layout、draw 是調度方法,由父容器調用,進行預處理.

在測量以前父元素都須要生成對應子view的測量規格MeasureSpec.具體見上一節.

3.1 measure過程

做用: 肯定測量寬高

measure-onMeasure-setMeasureDimension

複製代碼
1. 當子View是純View時,View的測量過程

onMeasure 實際測量方法

  1. 在onMeasure裏計算出本身的尺寸,經過setMeasureDimension保存測量尺寸,完成自我測量.
2. 當子View是ViewGroup時,ViewGroup的測量過程
  1. 在onMeasure裏,首先須要遍歷調用全部子view的measure方法,讓子View完成自我測量,依次遞歸.
    • 調用子view的measure方法以前需先獲取到子view的MeasureSpec,具體見上一節.
  2. 而後根據子View的尺寸,得出子View的位置,並保存尺寸和位置.
  3. 最後根據這些子View的尺寸位置,計算出本身尺寸,經過setMeasureDimension保存測量尺寸,完成自我測量.

對應源碼

//View.java
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //獲取默認值並保存
        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;//直接返回父元素可用空間,因此須要對wrap_content作特殊處理.
            break;
        }
        return result;
    }


//ViewGroup.java
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        //遍歷全部的子View
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();
        //得到子View的MeasureSpec
        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);
        //調用ziview的measure方法
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

複製代碼

3.2 layout過程

做用: 肯定最終寬高和位置

layout-onLayout
複製代碼
  • layout 保存傳入的位置,肯定了View自己在其父View中的位置.

  • 若是子View是純View,那麼在onLayout裏,什麼都不作.

  • 若是是ViewGroup,那麼在onLayout裏,首先須要遍歷調用全部子view的layout方法,讓子View完成自我佈局,依次遞歸.

對應源碼

@SuppressWarnings({"unchecked"})
    public void layout(int l, int t, int r, int b) {
        
        //...省略部分代碼
        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;
        
        //setFrame設置View四個頂點位置,肯定在父容器的位置
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            //開始佈局子view位置.
            onLayout(changed, l, t, r, b);

            if (shouldDrawRoundScrollbar()) {
                if(mRoundScrollbarRenderer == null) {
                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
                }
            } else {
                mRoundScrollbarRenderer = null;
            }

            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);
                }
            }
        }

        //...省略部分代碼
    }
複製代碼

從測量與佈局兩個階段能夠看出兩個特色.

  1. 測量階段由父View統一保存全部子View的尺寸位置信息(後面簡稱信息)
  2. 佈局階段由本身保存信息,該信息從父View傳進來.

3.3 draw過程

做用: 繪製到屏幕上

draw方法裏流程

  • drawBackground 繪製背景
  • onDraw 繪製本身
  • dispatchDraw 繪製子view
  • onDrawScrollBars 繪製裝飾

四. 自定義View的方式及注意事項

  • 基本方式:
  1. 繼承原生View
    • 繼承已存在的成熟控件(如:TextView)
  2. 繼承原生ViewGroup
    • 繼承已存在的成熟控件(如:LinearLayout)
  • 注意事項:
  1. 繼承原生的,不管是View仍是ViewGroup,都須要在onMeasure處理warp_content時狀況的寬高.
    • 對於view繪製時須要考慮padding.不然這些屬性都不生效.
    • 對於viewGroup測量和佈局時,須要考慮自身的padding和子view的margin.

因爲本人技術有限,若有錯誤的地方,麻煩你們給我提出來,本人不勝感激,你們一塊兒學習進步.

參考連接:

相關文章
相關標籤/搜索