Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 View 必讀:ViewRoot、MeasureSpec 與完整工作流程拆解

編輯:關於 Android 程式設計

ViewRoot 與 DecorView 的關係

ViewRoot 對應源碼中的 ViewRootImpl 類,它是連接 WindowManager 與 DecorView 的紐帶,View 的三大流程都由它來驅動。在 ActivityThread 中,Activity 對象創建完成後會把 DecorView 添加到 Window,同時創建 ViewRootImpl 並與 DecorView 建立關聯。

繪制流程從 ViewRoot 的 performTraversals 開始,依次經過 measure、layout、draw 三個階段,一個 View 才真正出現在屏幕上:measure 負責測量寬高,layout 確定它在父容器中的位置,draw 把它畫到屏幕。

performTraversals 內部會調用 performMeasure、performLayout、performDraw。以 measure 為例,performMeasure 調用 measure,measure 再調用 onMeasure,onMeasure 遍歷所有子元素——子元素重復同樣的過程,如此遞歸完成整棵 View 樹的測量。另外兩個流程同理。

三個階段各自的產物是:measure 決定 View 的寬高,之後可用 getMeasuredWidth / getMeasuredHeight 取值;layout 決定四個頂點坐標與最終寬高,可通過 getTop、getBottom、getLeft、getRight 獲取;draw 決定最終顯示內容。

DecorView 作為頂級 View,內部通常包含一個豎直方向的 LinearLayout,分為標題欄與內容欄兩部分(具體結構隨 Android 版本與主題而異)。setContentView 設置的布局其實就是被加進內容欄。DecorView 本質是一個 FrameLayout,所有 View 層事件都先經過它,再傳給我們自己的 View。

理解 MeasureSpec

MeasureSpec 在很大程度上決定了一個 View 的尺寸規格。測量時,系統會把 View 的 LayoutParams 按父容器施加的規則轉換成對應的 MeasureSpec,再依此測出寬高。

它是一個 32 位 int:高 2 位是 SpecMode(測量模式),低 30 位是 SpecSize(該模式下的規格大小)。

SpecMode 有三種:

1. UNSPECIFIED:父容器不施加任何限制,要多大給多大,一般用於系統內部。

2. EXACTLY:父容器已經確定了 View 的精確大小,最終尺寸就是 SpecSize,對應 LayoutParams 中的 match_parent 與具體數值。

3. AT_MOST:父容器指定了一個可用上限 SpecSize,View 不能超過它,對應 wrap_content。

由此可以推出幾條常用結論:View 寫死寬高時,不論父容器是什麼模式,它自身永遠是 EXACTLY 並遵循 LayoutParams;寫 match_parent 時,父容器是 EXACTLY 則子 View 也是 EXACTLY 並佔滿剩餘空間,父容器是 AT_MOST 則子 View 也是 AT_MOST;寫 wrap_content 時,不論父容器為何,子 View 一律是 AT_MOST 且不能超出剩餘空間。

換句話說,系統在測量時會在父容器約束下把 LayoutParams 轉化成 MeasureSpec,而子元素的 MeasureSpec 由父容器的 MeasureSpec 與自身的 LayoutParams 共同決定。


View 的工作流程

一、measure 過程

View 默認的 onMeasure 實現非常簡單:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(
        getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
        getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

setMeasuredDimension 設置測量後的寬高;getDefaultSize 返回的就是 SpecSize,也就是測量結果,絕大多數情況下與最終尺寸一致;getSuggestedMinimumWidth 提供建議寬度。

這裡藏著自定義 View 最常見的坑:直接繼承 View 而不重寫 onMeasure,布局裡寫 wrap_content 的效果等同於 match_parent。解法是在 onMeasure 中自行判斷模式,遇到 AT_MOST 時給定一個內部默認尺寸:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mWidth, mHeight);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mWidth, widthSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(heightSpecSize, mHeight);
    }
}

ViewGroup 的 measure 過程:

ViewGroup 除了完成自身測量,還要遍歷調用所有子元素的 measure。它是抽象類,並未重寫 onMeasure,而是提供了 measureChildren:遍歷子元素並調用 measureChild;measureChild 取出子元素的 LayoutParams,通過 getChildMeasureSpec 生成子元素的 MeasureSpec,再傳給 measure 完成測量。由於不同布局類型的排列特性差異很大,具體的 onMeasure 由各子類自行實現。

測量完成後可用 getMeasuredWidth / getMeasuredHeight 取值,但要注意某些極端情況下系統會多次 measure 才能定下最終尺寸,比較稳妥的做法是在 onLayout 中取值。

如何在 Activity 中正確拿到 View 的寬高

View 的測量與 Activity 生命週期並不同步,所以在 onCreate、onStart、onResume 裡直接取值往往拿到 0。四種可靠做法:

1. Activity/View#onWindowFocusChanged:此時 View 已初始化、寬高就緒。注意它會被多次回調,窗口獲得與失去焦點時都會觸發。

2. view.post(Runnable):把任務投遞到消息隊列尾部,Looper 執行它時 View 已完成初始化。

3. ViewTreeObserver:註冊 OnGlobalLayoutListener,當 View 樹狀態或內部可見性發生變化時回調 onGlobalLayout。同樣會被多次觸發。

4. 手動 view.measure:自己構造 MeasureSpec 後調用。match_parent 無法測出具體值(不知道父容器剩餘空間);具體數值用 EXACTLY;wrap_content 則用一個極大的 AT_MOST:

int widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
view.measure(widthMeasureSpec, heightMeasureSpec);

二、layout 過程

在 View 的默認實現中,測量寬高與最終寬高是相等的:前者形成於 measure,後者形成於 layout。

三、draw 過程

繪制大致分四步:繪製背景 background.draw(canvas)、繪製自身 onDraw、繪製子元素 dispatchDraw、繪製裝飾 onDrawScrollBars。子元素的繪製由 dispatchDraw 遍歷完成。若某個 View 不需要畫任何內容,可把 setWillNotDraw 設為 true 讓系統做優化——ViewGroup 默認就是 true,所以自定義 ViewGroup 若要在 onDraw 中畫東西,必須顯式關掉它。

自定義 View 實踐要點

直接繼承 View 或 ViewGroup 的控件,都要在 onMeasure 中對 wrap_content 做特殊處理。直接繼承 View 的控件若不在 onDraw 中處理 padding,padding 屬性就不生效;直接繼承 ViewGroup 的控件則要在 onMeasure 和 onLayout 中同時考慮 padding 與子元素 margin,否則兩者都無效。

另外兩條容易被忽略的經驗:View 內部提供了 post 系列方法,多數場景下完全可以替代 Handler;View 中啟動的線程與動畫,需要在 onDetachedFromWindow 中停止,否則容易泄漏。

示例一:繼承 View 畫一個圓

public class CircleView extends View {
    private int mColor = Color.RED;
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
        a.recycle();
        init();
    }

    private void init() {
        paint.setColor(mColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(200, 200);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(200, widthSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(heightSpecSize, 200);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingBottom - paddingTop;
        int radius = Math.min(width, height) / 2;
        canvas.drawCircle(width / 2 + paddingLeft, height / 2 + paddingTop, radius, paint);
    }
}

示例二:繼承 ViewGroup 做一個可水平滑動的容器

關鍵點在於 onInterceptTouchEvent 中判斷滑動方向、onTouchEvent 中 scrollBy、以及用 Scroller 配合 computeScroll 實現平滑收尾。

public class HorizontalScrollView extends ViewGroup {
    private int mChildrenSize;
    private int mChildWidth;
    private int mChildIndex;
    private int mLastX = 0, mLastY = 0;
    private int mLastXIntercept = 0, mLastYIntercept = 0;
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;

    private void init() {
        if (mScroller == null) {
            mScroller = new Scroller(getContext());
            mVelocityTracker = VelocityTracker.obtain();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean intercepted = false;
        int x = (int) ev.getX();
        int y = (int) ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                    intercepted = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastXIntercept;
                int deltaY = y - mLastYIntercept;
                intercepted = Math.abs(deltaX) > Math.abs(deltaY);
                break;
            default:
                break;
        }
        mLastX = x; mLastY = y;
        mLastXIntercept = x; mLastYIntercept = y;
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mVelocityTracker.addMovement(event);
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                scrollBy(-(x - mLastX), 0);
                break;
            case MotionEvent.ACTION_UP:
                int scrollX = getScrollX();
                mVelocityTracker.computeCurrentVelocity(1000);
                float xVelocity = mVelocityTracker.getXVelocity();
                if (Math.abs(xVelocity) > 50) {
                    mChildIndex = xVelocity > 0 ? mChildIndex - 1 : mChildIndex + 1;
                } else {
                    mChildIndex = (scrollX + mChildWidth / 2) / mChildWidth;
                }
                mChildIndex = Math.max(0, Math.min(mChildIndex, mChildIndex - 1));
                smoothScrollBy(mChildIndex * mChildWidth - scrollX, 0);
                mVelocityTracker.clear();
                break;
            default:
                break;
        }
        mLastY = y; mLastX = x;
        return true;
    }

    private void smoothScrollBy(int dx, int dy) {
        mScroller.startScroll(getScrollX(), 0, dx, 0, 500);
        invalidate();
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        mVelocityTracker.recycle();
        super.onDetachedFromWindow();
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved