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

Android View 繪製優化實務:精簡層級、複用佈局與硬體加速

編輯:關於 Android 程式設計

一個常見的誤解是:只要使用 LinearLayout、FrameLayout 這類基本佈局結構,大多數情況下就能得到高效率的版面。事實並非如此。應用裡加入的每一個控制項與每一層佈局,都需要初始化、量測(measure)、配置(layout)與繪製(draw)。

舉例來說,一層套一層的 LinearLayout 會製造出過深的佈局層級。更嚴重的是,多層使用 layout_weight 屬性的 LinearLayout 會帶來可觀的額外開銷,因為每個子視圖都得被量測兩次。在 ListView、GridView 這類會反覆解析佈局檔的場合,這個成本會被放大得非常明顯。

觀察你的佈局

Android SDK 工具箱中有一個名為 Hierarchy Viewer 的工具,可以在應用執行時分析佈局,幫助你找出效率瓶頸。

它能列出已連線裝置或模擬器上正在執行的行程,並呈現佈局樹。每個方塊下方的紅、綠、藍三色交通燈,分別代表量測、配置與繪製階段的效率,用來定位潛在問題。

假設 ListView 中的一項 Item 採用如下佈局:

Hierarchy Viewer 位於 <sdk>/tools 路徑下。開啟後會列出所有可用裝置與其上的行程,點擊 Load View Hierarchy 即可顯示所選元件的 UI 佈局層級。例如下圖就是前述佈局的層級樹:

可以直觀看出這個三層結構存在問題。點選項目後會顯示每個階段各自的耗時:

很明顯,最外層的 LinearLayout 花在量測、配置與繪製上的時間最長,值得優先優化。該佈局完成渲染的時間分別為:

量測:0.977ms

配置:0.167ms

繪製:2.717ms

修改佈局檔

低效的根源是內嵌的 LinearLayout。解法是「扁平化」——讓佈局變得更淺更寬,而不是更窄更深。以 RelativeLayout 作為根節點,就能達到同等視覺效果,同時把層級降到兩層:

改善後的耗時:

量測:0.977ms

配置:0.167ms

繪製:2.717ms

或許幅度看似微小,但別忘了 ListView 會對每一個 Item 都跑一次這個流程,累積下來的效果相當可觀。

多數時間差異來自使用了帶 layout_weight 屬性的 LinearLayout,它會拖慢量測速度。這只是一個例子:每種佈局都該用在合適的位置,也該認真思考是否真的需要 layout_weight。

使用 Lint 工具

好的習慣是讓 Lint 檢查佈局檔,找出可優化的層級。Lint 已取代舊的 layoutopt 工具,功能更強。幾條常用規則:

1、使用複合控制項——包含一個 ImageView 與一個 TextView 的 LinearLayout,若合併成自訂複合控制項會更有效率。

2、合併作為根節點的 FrameLayout——若 FrameLayout 是佈局檔的根節點,且沒有背景圖或 padding,用 <merge /> 取代 <FrameLayout /> 會更好。

3、無用的葉節點——通常沒有子視圖也沒有背景的佈局控制項可以移除(例如處於 invisible 狀態者)。

4、無用的父節點——若某個父視圖有子視圖但沒有兄弟節點、不是 ScrollView 或根節點、也沒有背景圖,同樣可以移除;移除後其子視圖直接上移到原父層級,解析與配置都會更有效率。

5、過深的佈局層級——內嵌過多佈局必定低效。可考慮 RelativeLayout、GridLayout 這類扁平容器來改善。預設建議的最大深度為 10。

在 Eclipse 環境下,Lint 能自動修正部分問題、提供建議並直接跳到出錯的程式碼。若沒有用 Eclipse,也可以透過命令列執行。

用 <include /> 複用佈局

Android 內建了各種小型可複用的互動元素,但你有時需要複用更大的區塊,也就是整份佈局檔。為了有效率地複用,可以使用 <include /> 與 <merge /> 標籤把其他佈局檔併入當前的佈局。

複用佈局是很強大的手法,讓你能建立可重複使用的元件。例如一個「是/否」的 Button 面板,或一段帶文字說明的 ProgressBar。複用也意味著應用中的元素可以從龐雜的佈局檔中抽出來獨立管理,之後只需在需要處引入即可。當你以自訂 View 建立獨立 UI 元件時,搭配佈局複用會輕鬆許多。

1、建立可複用的佈局檔

先想清楚這個區塊長什麼樣子,再建立並命名(以 .xml 結尾)。以下來自 G-Kenya codelab 的 titlebar.xml,定義了每個 Activity 都會用到的自訂標題欄。由於它會被併入其他佈局,其根視圖最好精確指定寬高:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/gafricalogo" />
</FrameLayout>

2、使用 <include />

在需要它的地方用 <include /> 引入:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="center_horizontal">
    <include layout="@layout/titlebar"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:padding="10dp" />
    ...
</LinearLayout>

你也可以在 <include /> 節點上為被引入佈局的根視圖指定 id,並覆寫所有版面參數(任何以 android:layout_ 為前綴的屬性):

<include android:id="@+id/news_title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    layout="@layout/title"/>

3、使用 <merge />

複用佈局時,<merge /> 能在層級中消除多餘的視圖節點。舉例來說,若主佈局是一個垂直排列兩個 Button 的 LinearLayout,你想把它複用進其他佈局——但任何包含多個子元素的佈局檔都必須有根視圖,否則編譯會報錯。若在可複用佈局中補上一層 LinearLayout 當根,就會變成「垂直 LinearLayout 裡再嵌一個垂直 LinearLayout」,除了拖慢 UI 效率之外毫無意義。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="horizontal">
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/add"/>
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/delete"/>
</LinearLayout>

要避免這種冗餘,就把 <merge /> 當作可複用佈局的根節點:

<merge xmlns:android="https://schemas.android.com/apk/res/android">
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/add"/>
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/delete"/>
</merge>

如此一來,當你以 <include /> 引入這份佈局時,系統會忽略 <merge /> 節點,直接把兩個 Button 放進 <include /> 的位置。

越少越好

要加速視圖,就從呼叫頻繁的地方刪掉不必要的程式碼。繪製從 onDraw() 開始,在這裡優化收益最大。尤其應避免在 onDraw() 中配置記憶體,因為任何配置都可能觸發垃圾回收,造成畫面不連貫。把物件配置安排在初始化階段或動畫之間,絕不要在動畫執行時配置記憶體。

另一方面則是減少 onDraw() 的呼叫次數。invalidate() 會觸發 onDraw(),所以要避免不必要的呼叫;如果可以,改用帶參數的 invalidate() 重載版本,而非無參數版本。帶參數的版本能讓繪製流程更精準,跳過落在該矩形區域外的視圖,減少無謂重繪。

invalidate() 的三個重載版本:

1、public void invalidate(Rect dirty)

2、public void invalidate(int l, int t, int r, int b)

3、public void invalidate()

另一個高成本操作是配置(layout)。每當你對某個 View 呼叫 requestLayout(),Android UI 框架就得遍歷整棵 View 樹,逐一確定各視圖的尺寸;若量測過程中出現衝突,可能還得多次遍歷。有些 UI 設計為了達到特定視覺效果而做出很深的 ViewGroup 層級,代價就是效率。請盡量確保 View 樹夠淺。

若 UI 設計確實複雜,可以考慮自訂 ViewGroup 來掌控配置流程。與內建容器不同,自訂 ViewGroup 能假定每個子 View 的大小與形狀,從而跳過對子 View 逐一量測的步驟。PieChart 就是例子:它繼承 ViewGroup,含有子 View,卻從不量測它們,而是依自己的配置演算法直接設定子 View 尺寸。

/**
 * Custom view that shows a pie chart and, optionally, a label.
 */
public class PieChart extends ViewGroup {
    ...
    // Measurement functions. This example uses a simple heuristic: it assumes that
    // the pie chart should be at least as wide as its label.
    @Override
    protected int getSuggestedMinimumWidth() {
        return (int) mTextWidth * 2;
    }

    @Override
    protected int getSuggestedMinimumHeight() {
        return (int) mTextWidth;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Try for a width based on our minimum
        int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
        int w = Math.max(minw, MeasureSpec.getSize(widthMeasureSpec));

        // Whatever the width ends up being, ask for a height that would let the pie
        // get as big as it can
        int minh = (w - (int) mTextWidth) + getPaddingBottom() + getPaddingTop();
        int h = Math.min(MeasureSpec.getSize(heightMeasureSpec), minh);
        setMeasuredDimension(w, h);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // Do nothing. Do not call the superclass method--that would start a layout pass
        // on this view's children. PieChart lays out its children in onSizeChanged().
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        // Set dimensions for text, pie chart, etc
        // Account for padding

        // Lay out the child view that actually draws the pie.
        mPieView.layout((int) mPieBounds.left, (int) mPieBounds.top,
                        (int) mPieBounds.right, (int) mPieBounds.bottom);
        mPieView.setPivot(mPieBounds.width() / 2, mPieBounds.height() / 2);
        mPointerView.layout(0, 0, w, h);
        onDataChanged();
    }
}

這裡的關鍵是 onLayout() 刻意留空、不呼叫父類別實作,避免觸發新一輪的子 View 配置流程;實際的配置改在 onSizeChanged() 中依自身演算法一次完成。

使用硬體加速

從 Android 3.0 起,2D 圖形庫在多數裝置上可由 GPU 加速。硬體加速能大幅優化多數應用,但並非每個應用都適合,框架把決定權交給了你。

要啟用它,必須在 AndroidManifest.xml 中把 targetSdkVersion 設為 11 以上:

<uses-sdk android:targetSdkVersion="11"/>

啟用後你可能感受不到明顯提升。Mobile GPU 擅長特定任務,例如縮放、旋轉、平移圖片;也有不擅長的工作,例如繪製直線或曲線。物盡其用、揚長避短——盡量讓 GPU 處理它擅長的部分。

以 PieChart 為例,繪製圓形相對耗費資源,每次旋轉引起的重繪會讓 UI 遲鈍。解法是讓 View 負責呈現該圓形,並把它的 layer type 設為 LAYER_TYPE_HARDWARE,使 GPU 能快取靜態圖像。示例中該 View 作為 PieChart 的內部類別存在,減少了實作成本。

private class PieView extends View {
    public PieView(Context context) {
        super(context);
        if (!isInEditMode()) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (Item it : mData) {
            mPiePaint.setShader(it.mShader);
            canvas.drawArc(mBounds, 360 - it.mEndAngle, it.mEndAngle - it.mStartAngle, true, mPiePaint);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        mBounds = new RectF(0, 0, w, h);
    }

    RectF mBounds;
}

改過之後,只有第一次顯示時才會執行 PieChart.PieView.onDraw();其餘時間,繪製結果作為圖片快取,重繪時由 GPU 直接旋轉圖像。

不過這是一種折衷。把圖片快取成硬體層會佔用 video memory,而 video memory 是受限資源。因此 PieChart.PieView 的最終版本只在使用者滑動時才把 layer type 設為 LAYER_TYPE_HARDWARE,其他時間設為 LAYER_TYPE_NONE,讓 GPU 停止快取圖片、釋放記憶體。

最後別忘了持續分析你的程式碼。在一個 View 上有效的優化手法,套到另一個 View 上未必合適,甚至可能適得其反。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved