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

Android 布局優化:Merge、Include、ViewStub 的使用與源碼分析

編輯:關於 Android 程式設計

開發中 UI 布局是大家都會遇到的問題。隨著界面越來越多,布局的重複性與複雜度也會隨之增長。Android 官方提供了幾個優化方法,但網路上的資料大多是對官方文件的翻譯,講解特別簡單,遇到問題時常常知其然而不知其所以然。本文就對這些問題做更詳細的說明。

Include

用得最多的應該是 include,按官方的意思,它主要用來解決重複定義相同布局的問題。例如你有五個界面,每個界面頂部都有一模一樣的返回按鈕和文本控件,不使用 include 時你得在每個界面重複書寫相同的頂部欄,相當煩人。使用 include 標簽,只需把這個被反覆使用的頂部欄獨立成一個 XML 檔案,然後在需要的地方透過 include 引入即可,就像 C/C++ 中的 include 頭檔一樣,達到復用的目的。

my_title_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/my_title_parent_id"
    android:layout_height="wrap_content" >
    <ImageButton
        android:id="@+id/back_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <TextView
        android:id="@+id/title_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/back_btn"
        android:gravity="center"
        android:text="我的 title"
        android:textSize="18sp" />
</RelativeLayout>

使用 include 引入布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <include
        android:id="@+id/my_title_ly"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/my_title_layout" />
</LinearLayout>

注意事項

1、使用 include 最常見的問題就是 findViewById 找不到目標控件,正確用法如下:

View titleView = findViewById(R.id.my_title_ly);
TextView titleTextView = (TextView) titleView.findViewById(R.id.title_tv);
titleTextView.setText("new Title");

首先找到 include 的 id(此處為 my_title_ly),再透過 titleView.findViewById 查找目標布局中的子控件。也就是說,我們可以為 include 標簽設置 id,透過這個 id 取得 include 對應的 View 後,再對它進行 findViewById 才能正確查找。

如果你設置了 include 的 id,卻用被 include 布局的根 View id 來查找子元素,就會出錯:

View titleView = findViewById(R.id.my_title_parent_id);
TextView titleTextView = (TextView) titleView.findViewById(R.id.title_tv);
titleTextView.setText("new Title");

這樣會報空指標異常,因為 titleView 根本找不到。

這是為什麼呢?我們來分析源碼。布局檔案的解析最終都會呼叫到 LayoutInflater 的 inflate 方法,該方法最終又會呼叫 rInflate:

void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs, boolean finishInflate)
        throws XmlPullParserException, IOException {
    final int depth = parser.getDepth();
    int type;
    // 迭代 xml 中的所有元素,挨個解析
    while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
            && type != XmlPullParser.END_DOCUMENT) {
        if (type != XmlPullParser.START_TAG) {
            continue;
        }
        final String name = parser.getName();
        if (TAG_REQUEST_FOCUS.equals(name)) {
            parseRequestFocus(parser, parent);
        } else if (TAG_INCLUDE.equals(name)) {
            // 如果節點是 include 節點,則呼叫 parseInclude 方法
            if (parser.getDepth() == 0) {
                throw new InflateException("<include /> cannot be the root element");
            }
            parseInclude(parser, parent, attrs);
        } else if (TAG_MERGE.equals(name)) {
            throw new InflateException("<merge /> must be the root element");
        } else {
            final View view = createViewFromTag(parent, name, attrs);
            final ViewGroup viewGroup = (ViewGroup) parent;
            final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
            rInflate(parser, view, attrs, true);
            viewGroup.addView(view, params);
        }
    }
    if (finishInflate) parent.onFinishInflate();
}

這個方法遍歷 xml 中的所有元素並逐一解析。遇到 include 標簽時,會呼叫 parseInclude 函數,我們來看看它:

private void parseInclude(XmlPullParser parser, View parent, AttributeSet attrs)
        throws XmlPullParserException, IOException {
    int type;
    if (parent instanceof ViewGroup) {
        final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
        if (layout == 0) {
            // include 標簽中沒有設置 layout 屬性,會拋出異常
            ...
        } else {
            final XmlResourceParser childParser = getContext().getResources().getLayout(layout);
            try {
                final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
                while ((type = childParser.next()) != XmlPullParser.START_TAG
                        && type != XmlPullParser.END_DOCUMENT) {
                    // 空循環
                }
                final String childName = childParser.getName();
                if (TAG_MERGE.equals(childName)) {
                    rInflate(childParser, parent, childAttrs, false);
                } else {
                    // 首先根據 include 的屬性集創建被 include 進來的布局的根 view
                    final View view = createViewFromTag(parent, childName, childAttrs);
                    final ViewGroup group = (ViewGroup) parent;
                    ViewGroup.LayoutParams params = null;
                    try {
                        params = group.generateLayoutParams(attrs);
                    } catch (RuntimeException e) {
                        params = group.generateLayoutParams(childAttrs);
                    } finally {
                        if (params != null) {
                            view.setLayoutParams(params);
                        }
                    }
                    // 解析所有子控件
                    rInflate(childParser, view, childAttrs, true);
                    // 嘗試用 include 標簽上的 android:id 覆蓋被引入布局的 id
                    TypedArray a = mContext.obtainStyledAttributes(
                            attrs, com.android.internal.R.styleable.View, 0, 0);
                    int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
                    int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
                    a.recycle();
                    // 將 include 中設置的 id 設置給根 view
                    if (id != View.NO_ID) {
                        view.setId(id);
                    }
                    switch (visibility) {
                        case 0: view.setVisibility(View.VISIBLE); break;
                        case 1: view.setVisibility(View.INVISIBLE); break;
                        case 2: view.setVisibility(View.GONE); break;
                    }
                    group.addView(view);
                }
            } finally {
                childParser.close();
            }
        }
    }
    ...
}

關鍵在最後那段:當 include 標簽設置了 id(且不為 View.NO_ID)時,系統會把該 id 設置給被引入布局的根元素。也就是說,在我們的例子中,原本 id 為 my_title_parent_id 的 RelativeLayout,其 id 會被動態改成 include 標簽中的 my_title_ly。因此,此時再用 my_title_parent_id 去查找根元素自然會找不到!

結論就是:如果 include 中設置了 id,就透過 include 的 id 查找被 include 布局根元素的 View;如果 include 中沒設置 id,而被 include 布局的根元素設置了 id,則透過該根元素的 id 查找即可。拿到根元素後,再查找其子控件的方式都是一樣的。

ViewStub

先看官方說明:ViewStub is a lightweight view with no dimension and doesn't draw anything or participate in the layout. As such, it's cheap to inflate and cheap to leave in a view hierarchy. Each ViewStub simply needs to include the android:layout attribute to specify the layout to inflate.

其實 ViewStub 就是一個寬高都為 0 的 View,預設不可見,只有透過呼叫 setVisibility 或 inflate 函數才會把它要裝載的目標布局加載出來,從而達到延遲加載的效果。目標布局透過 android:layout 屬性設置。例如我們可以用一個 ViewStub 惰性加載一個消息流的評論列表——因為一個帖子可能沒有評論,此時可以不加載這個 ListView,只有真的有評論時才加載出來,這樣就省去了加載 ListView 帶來的資源消耗與延時。

<ViewStub
    android:id="@+id/stub_import"
    android:inflatedId="@+id/stub_comm_lv"
    android:layout="@layout/my_comment_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" />

my_comment_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/my_comm_lv"
    android:layout_height="match_parent" >
</ListView>

運行時,我們只需控制 id 為 stub_import 的 ViewStub 的可見性,或呼叫 inflate() 函數來決定是否加載評論列表。方式一透過 setVisibility 加載:

public class MainActivity extends Activity {
    public void onCreate(Bundle b) {
        setContentView(R.layout.main);
        // 方式一:獲取 ViewStub
        ViewStub listStub = (ViewStub) findViewById(R.id.stub_import);
        // 加載評論列表布局
        listStub.setVisibility(View.VISIBLE);
        // 注意這裡是透過 ViewStub 的 inflatedId 來獲取
        ListView commLv = findViewById(R.id.stub_comm_lv);
        if (listStub.getVisibility() == View.VISIBLE) {
            // 已經加載
        }
    }
}

要獲取評論 ListView 時,並不是用 ViewStub 的 id,而是用它的 inflatedId,這又是為什麼呢?我們看 ViewStub 的部分源碼:

public View inflate() {
    final ViewParent viewParent = getParent();
    if (viewParent != null && viewParent instanceof ViewGroup) {
        if (mLayoutResource != 0) {
            final ViewGroup parent = (ViewGroup) viewParent;
            final LayoutInflater factory = LayoutInflater.from(mContext);
            final View view = factory.inflate(mLayoutResource, parent, false);
            // 如果 ViewStub 的 inflatedId 不為 NO_ID,則把它設置為目標布局根元素的 id
            if (mInflatedId != NO_ID) {
                view.setId(mInflatedId);
            }
            final int index = parent.indexOfChild(this);
            parent.removeViewInLayout(this); // 將 ViewStub 自身從 parent 中移除
            final ViewGroup.LayoutParams layoutParams = getLayoutParams();
            if (layoutParams != null) {
                parent.addView(view, index, layoutParams);
            } else {
                parent.addView(view, index);
            }
            mInflatedViewRef = new WeakReference<View>(view);
            if (mInflateListener != null) {
                mInflateListener.onInflate(this, view);
            }
            return view;
        }
    }
    ...
}

可見最終加載目標布局的還是 inflate() 函數:加載後取得根元素,若 mInflatedId 不為 NO_ID 就把它設置為根元素的 id,這就是為什麼我們用 findViewById(R.id.stub_comm_lv) 來獲取評論 ListView——其中的 stub_comm_lv 正是 ViewStub 的 inflatedId。當然若你沒設置 inflatedId,還是可以透過評論列表本身的 id 獲取。此外,ViewStub 會從 parent 中被移除,再把目標布局的根元素添加進去,最後返回該根元素,因此呼叫 inflate() 時可直接取得返回值,省掉 findViewById 的過程。

方式二直接呼叫 inflate() 方法:

public class MainActivity extends Activity {
    ListView commLv2 = null; // 成員變量

    public void onCreate(Bundle b) {
        setContentView(R.layout.main);
        ViewStub listStub2 = (ViewStub) findViewById(R.id.stub_import);
        if (commLv2 == null) {
            // inflate 函數直接返回 ListView 對象
            commLv2 = (ListView) listStub2.inflate();
        }
    }
}

注意事項:判斷是否已加載時,若用 setVisibility 加載可透過判斷可見性,若用 inflate() 加載則需用方式二判斷;findViewById 時要留意是否設置了 inflatedId,若設置了則用它查找根元素。

Merge

先看官方說明:The <merge /> tag helps eliminate redundant view groups in your view hierarchy when including one layout within another. ... The nested LinearLayout serves no real purpose other than to slow down your UI performance.

它的作用就是減少 include 布局時的層級。有趣的是,在 Android 源碼裡,Merge 竟然對應著一個 Activity:

public class Merge extends Activity {
    private LinearLayout mLayout;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mLayout = new LinearLayout(this);
        mLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutInflater.from(this).inflate(R.layout.merge_tag, mLayout);
        setContentView(mLayout);
    }

    public ViewGroup getLayout() {
        return mLayout;
    }
}

使用 merge 組織子元素可以減少布局層級。例如復用一個含多個子控件的布局時,通常需要一個 ViewGroup 來管理,像這樣:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_gravity="center_horizontal|bottom"
        android:padding="12dip"
        android:background="#AA000000"
        android:textColor="#ffffffff"
        android:text="Golden Gate" />
</FrameLayout>

透過 include 引入時就會多引入一個 FrameLayout 層級:

改用 merge 標簽就會消除多餘的 FrameLayout 層級:

<merge xmlns:android="https://schemas.android.com/apk/res/android">
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_gravity="center_horizontal|bottom"
        android:padding="12dip"
        android:background="#AA000000"
        android:textColor="#ffffffff"
        android:text="Golden Gate" />
</merge>

效果圖如下:

它是如何實現的呢?相關源碼同樣在 LayoutInflater 的 inflate() 中:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        View result = root;
        try {
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG
                    && type != XmlPullParser.END_DOCUMENT) {
                // 空循環
            }
            final String name = parser.getName();
            // 如果是 merge 標簽,則呼叫 rInflate 進行解析
            if (TAG_MERGE.equals(name)) {
                if (root == null || !attachToRoot) {
                    throw new InflateException("<merge /> can be used only with a valid "
                            + "ViewGroup root and attachToRoot=true");
                }
                rInflate(parser, root, attrs, false);
            } else {
                // 其他情況省略
            }
        } catch (XmlPullParserException e) {
            // 省略
        }
        return result;
    }
}

簡單來說,遇到 merge 標簽時,系統直接把其中的子元素添加到 merge 標簽的 parent 中,這樣就保證不會引入額外的層級。這正是 merge 能夠優化布局、提升 UI 效能的原理所在。

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