編輯:Android 資訊
做開發時 UI 佈局是繞不開的話題。隨著頁面變多,佈局的重複與複雜度也會同步上升。Android 官方提供了幾個優化手段,但網路上的資料多半是官方文檔的翻譯,講得很淺,一旦出問題就不知道所以然。這篇文章試著把細節講透,也歡迎大家留言交流。
最常用的應該是 include,它解決的是「同一段佈局在多處重複定義」的問題。假設你有五個頁面,頂部都是一模一樣的返回按鈕加標題文字,不用 include 就得在每份 XML 裡重抄一遍,非常噁心。有了 include,只要把頂欄抽成獨立 XML,需要的地方引入即可,概念上有點像 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>
引入它的佈局檔:
<?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>
這是用 include 時最常踩的坑。正確寫法是先找到 include 的 id,再往下找子控制項:
View titleView = findViewById(R.id.my_title_ly);
TextView titleTextView = (TextView) titleView.findViewById(R.id.title_tv);
titleTextView.setText("new Title");
也就是說,include 標籤上的 id 會「覆蓋」被引入佈局根元素的 id。如果你反過來用被引入佈局的根元素 id 去找:
View titleView = findViewById(R.id.my_title_parent_id); // 找不到,回傳 null
TextView titleTextView = (TextView) titleView.findViewById(R.id.title_tv);
titleTextView.setText("new Title");
就會拿到空指標而崩潰。為什麼?我們直接看源碼。佈局解析最終都會走到 LayoutInflater.inflate(),再進入 rInflate():
/**
* Recursive method used to descend down the xml hierarchy and instantiate
* views, instantiate their children, and then call onFinishInflate().
*/
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 if (TAG_1995.equals(name)) {
final View view = new BlinkLayout(mContext, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true);
viewGroup.addView(view, params);
} 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 元素並逐一解析:碰到某個標籤,就依 layout_width、layout_height、id 等屬性建構對應物件,再掛到父容器中。碰到 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 屬性,直接拋異常
final String value = attrs.getAttributeValue(null, "layout");
if (value == null) {
throw new InflateException("You must specifiy a layout in the"
+ " include tag: <include layout=/"@layout/layoutID/" />");
} else {
throw new InflateException("You must specifiy a valid layout "
+ "reference. The layout ID " + value + " is not valid.");
}
} else {
final XmlResourceParser childParser = getContext().getResources().getLayout(layout);
try {
// 取得屬性集,也就是 include 標籤上設定的屬性
final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
while ((type = childParser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
// Empty.
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(childParser.getPositionDescription()
+ ": No start tag found!");
}
// 1、解析 include 中的第一個元素
final String childName = childParser.getName();
if (TAG_MERGE.equals(childName)) {
// 若第一個元素是 merge,直接 rInflate 解析
rInflate(childParser, parent, childAttrs, false);
} else {
// 2、依 include 的屬性集建立被引入佈局的根 view
// 這裡對應 my_title_layout.xml 中的 RelativeLayout
final View view = createViewFromTag(parent, childName, childAttrs);
final ViewGroup group = (ViewGroup) parent;
ViewGroup.LayoutParams params = null;
try {
// 3、取得佈局參數
params = group.generateLayoutParams(attrs);
} catch (RuntimeException e) {
params = group.generateLayoutParams(childAttrs);
} finally {
if (params != null) {
view.setLayoutParams(params);
}
}
// 4、解析所有子控制項
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();
// 5、把 include 上設定的 id 賦給根 view
// 因此 my_title_layout.xml 中 RelativeLayout 的 id
// 會被改成 include 標籤上的 id
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;
}
// 6、把根 view 掛到父容器
group.addView(view);
}
} finally {
childParser.close();
}
}
} else {
throw new InflateException("<include /> can only be used inside of a ViewGroup");
}
final int currentDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
// Empty
}
}
關鍵就在第 5 步:只要 include 標籤上寫了 id,它就會被強制賦給被引入佈局的根元素。所以在我們的例子裡,那個原本 id 為 my_title_parent_id 的 RelativeLayout,執行期 id 已經被改成 my_title_ly,你當然找不到舊 id。
結論整理一下:
拿到根 view 之後,往下找子控制項的方式兩者一致。
先看官方說法:
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 指定。
舉個實用場景:信息流底下的評論列表。很多貼子根本沒有評論,那就沒必要每次都把 ListView 建起來。用 ViewStub 就能做到「有評論才載入」,省下資源與啟動延時:
<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>
執行期只要控制 ViewStub 的可見性,或直接呼叫 inflate(),就能決定要不要載入:
public class MainActivity extends Activity {
public void onCreate(Bundle b){
// main.xml 中包含上面的 ViewStub
setContentView(R.layout.main);
// 方式一:透過可見性觸發載入
ViewStub listStub = (ViewStub) findViewById(R.id.stub_import);
listStub.setVisibility(View.VISIBLE);
// 注意:這裡用的是 ViewStub 的 inflatedId,而不是 stub_import
ListView commLv = findViewById(R.id.stub_comm_lv);
if ( listStub.getVisibility() == View.VISIBLE ) {
// 已經載入
} else {
// 尚未載入
}
}
}
為什麼取 ListView 時用的是 stub_comm_lv 而不是 ViewStub 自己的 id?看源碼就明白了:
@SuppressWarnings({"UnusedDeclaration"})
public ViewStub(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.ViewStub, defStyle, 0);
// 取得 inflatedId 屬性
mInflatedId = a.getResourceId(R.styleable.ViewStub_inflatedId, NO_ID);
mLayoutResource = a.getResourceId(R.styleable.ViewStub_layout, 0);
a.recycle();
a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.View, defStyle, 0);
mID = a.getResourceId(R.styleable.View_id, NO_ID);
a.recycle();
initialize(context);
}
private void initialize(Context context) {
mContext = context;
setVisibility(GONE); // 預設不可見
setWillNotDraw(true); // 不參與繪製
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(0, 0); // 寬高皆為 0
}
@Override
public void setVisibility(int visibility) {
if (mInflatedViewRef != null) {
// 已載入過,只需改可見性
View view = mInflatedViewRef.get();
if (view != null) {
view.setVisibility(visibility);
} else {
throw new IllegalStateException("setVisibility called on un-referenced view");
}
} else {
// 尚未載入,先設定自身可見性再觸發 inflate
super.setVisibility(visibility);
if (visibility == VISIBLE || visibility == INVISIBLE) {
inflate();
}
}
}
/**
* Inflates the layout resource identified by {@link #getLayoutResource()}
* and replaces this StubbedView in its parent by the inflated layout resource.
*/
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);
// 1、載入目標佈局
final View view = factory.inflate(mLayoutResource, parent, false);
// 2、若 inflatedId 有效,把它設為目標佈局根元素的 id
if (mInflatedId != NO_ID) {
view.setId(mInflatedId);
}
final int index = parent.indexOfChild(this);
// 3、把 ViewStub 自身從父容器中移除
parent.removeViewInLayout(this);
final ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != null) {
// 4、把目標佈局根元素掛到原本的位子
parent.addView(view, index, layoutParams);
} else {
parent.addView(view, index);
}
mInflatedViewRef = new WeakReference<View>(view);
if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
}
return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
}
所以真正幹活的是 inflate():載入目標佈局,若 mInflatedId 有效就把它寫成根元素的 id(這正是 findViewById(R.id.stub_comm_lv) 能拿到 ListView 的原因),接著把自己從父容器摘掉,再把新 view 放回原位置。若沒設 inflatedId,仍然可以用 findViewById(R.id.my_comm_lv) 找到。
另一種用法是直接呼叫 inflate(),它會把根元素回傳給你,省掉 findViewById:
public class MainActivity extends Activity {
// 把 commLv2 設為類的成員變數
ListView commLv2 = null;
public void onCreate(Bundle b){
setContentView(R.layout.main);
// 方式二:直接呼叫 inflate
ViewStub listStub2 = (ViewStub) findViewById(R.id.stub_import);
if ( commLv2 == null ) {
// 尚未載入,inflate 直接回傳 ListView
commLv2 = (ListView) listStub2.inflate();
} else {
// 已經載入過
}
}
}
官方說明:
The <merge /> tag helps eliminate redundant view groups in your view hierarchy when including one layout within another. For example, if your main layout is a vertical LinearLayout in which two consecutive views can be re-used in multiple layouts, then the re-usable layout in which you place the two views requires its own root view. However, using another LinearLayout as the root for the re-usable layout would result in a vertical LinearLayout inside a vertical LinearLayout. The nested LinearLayout serves no real purpose other than to slow down your UI performance.
簡單說就是消除 include 時多出來的那層無意義容器。有趣的是,Android 裡甚至有一個叫 Merge 的 Activity 專門用來測試驗證這個標籤:
/**
* Exercise <merge /> tag in XML files.
*/
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;
}
}
場景是這樣的:當我們要複用一個含多個子控制項的佈局時,通常得包一層 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);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
if (TAG_MERGE.equals(name)) {
// merge 必須搭配有效的 root 且 attachToRoot=true
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
// 直接解析 merge 的子元素
rInflate(parser, root, attrs, false);
} else {
// 代碼省略
}
} catch (XmlPullParserException e) {
// 代碼省略
}
return result;
}
}
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
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)) {
// 代碼省略
parseInclude(parser, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else if (TAG_1995.equals(name)) {
final View view = new BlinkLayout(mContext, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true);
viewGroup.addView(view, params);
} else {
// 我們的例子會走到這裡
final View view = createViewFromTag(parent, name, attrs);
// 取得 merge 標籤的 parent
final ViewGroup viewGroup = (ViewGroup) parent;
// 取得佈局參數
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 遞歸解析每個子元素
rInflate(parser, view, attrs, true);
// 直接把子元素掛到 merge 的 parent 上
viewGroup.addView(view, params);
}
}
if (finishInflate) parent.onFinishInflate();
}
原理其實很樸素:遇到 merge 就把它的子元素直接掛到 merge 的父容器上,因此不會多產生任何層級。也正因為如此,merge 只能作為 XML 的根節點,而且必須搭配一個有效的 root ViewGroup 並把 attachToRoot 設為 true。
開發過程中,與其背下結論,不如把常用技術點背後的機制搞明白。知道為什麼,出問題時才不至于束手無策——這也是技術成長最踏實的路徑。
從電源轉換看 Android ListView 的適配器模式
模式定義 適配器模式把一個類的接口轉換成客戶端期待的另外一種接口,從而使原本因接口不匹配而無法協同工作的兩個類能夠一起運作。 什麼時候需要它 最直觀的例子是電源。筆記本
Android 開發架構思考與實踐總結
從代碼重構到架構思考 在 Android 項目開發中,很多團隊一開始只關注功能實現,等到需求不斷堆疊、缺陷反覆出現,才意識到代碼結構的混亂已經拖累迭代效率。僅僅從 MVC
Android 非同步訊息機制:Handler、Looper 與 MessageQueue
Android 的 UI 操作通常必須在主執行緒進行,而耗時工作又不能阻塞主執行緒。為了解決這個矛盾,Android 提供了以 Handler、Looper、Messag
AndroidEventBus 的高階玩法:解耦、退出應用與自定義事件處理器
顧名思義,AndroidEventBus 是一個面向 Android 平台的事件總線框架。它簡化了 Activity、Fragment、Service 之間的交互,大幅降