編輯:關於 Android 程式設計
我們都知道,在 Activity#setContentView() 中會呼叫 PhoneWindow#setContentView(),而其中有這麼一句 mLayoutInflater.inflate(layoutResID, mContentParent),作用是把 activity_main.xml 填充進 mContentParent。寫 adapter 時也常寫 mInflater.inflate(layoutResID, null)。那麼,這行程式碼究竟是如何把 XML 檔轉換成 View 或 ViewGroup 的呢?本文就循著源碼一探究竟。
取得方式有兩種:LayoutInflater.from(Context context) 與 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)。其實兩者是同一回事,先看 from():
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
可見 from() 只是對第二種方式的簡單封裝。Context 的實作類是 ContextImpl,跟進 getSystemService():
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
再跟進 SystemServiceRegistry#getSystemService():
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
它直接從全域變數 SYSTEM_SERVICE_FETCHERS 依名字取得 fetcher,再由 fetcher 取得 LayoutInflater。而這個 fetcher 是在 SystemServiceRegistry 的靜態區塊中註冊的:
static {
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}
});
}
由於 createService() 回傳的是 PhoneLayoutInflater,所以後文使用的一直是它的物件。而 CachedServiceFetcher 會把建立好的服務快取起來,下次直接取用,不必重複建立。取得物件後,接著呼叫 inflate()。
先看在 setContentView 中的 inflate(layoutResID, mContentParent):
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
這裡以 root 是否為 null 決定第三個參數:root 為 null 則 attachToRoot 為 false;root 不為 null 則為 true。這正好對應 setContentView 與 adapter 中 inflate(layoutResID, null) 兩種情況。接著跟進核心的三參數版本:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
它先取得 XML 解析器,再呼叫最關鍵的 inflate(XmlPullParser, ...):
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
View result = root;
try {
// 取得根節點名稱,例如 LinearLayout
final String name = parser.getName();
if (TAG_MERGE.equals(name)) {
// 根節點為 merge 開頭
...
} else {
// 建立根檢視
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// 遍歷解析子 View 並加入根節點 temp
rInflateChildren(parser, temp, attrs, true);
// root 不為空且 attachToRoot 為 true,直接加入 root
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// root 為 null 或 attachToRoot 為 false,直接回傳 temp
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (Exception e) {
...
}
return result;
}
}
這段程式碼釐清了 inflate(resId, null) 與 inflate(resId, root) 的差異:當 root 為 null,最終回傳的是解析出來的根 View,且 attachToRoot 為 false;當 root 不為 null 且 attachToRoot 為 true,則會把根 View 直接加入 root。
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr) {
...
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
...
return view;
}
再跟進 createView():
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor extends View> constructor = sConstructorMap.get(name);
Class extends View> clazz = null;
try {
if (constructor == null) {
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
}
final View view = constructor.newInstance(args);
return view;
} catch (Exception e) {
...
}
}
sConstructorMap 是個 HashMap。程式碼先依根節點名稱(如 LinearLayout)查找快取的建構子,第一次執行時回傳 null,於是透過反射取得建構方法、強制設為可存取後存入 map;之後就能直接取出使用,最後呼叫 newInstance 反射出根節點 View 實例。
取得根節點後,接著遍歷子 View。rInflateChildren() 只是簡單轉發給 rInflate():
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs, boolean finishInflate)
throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
核心的遍歷邏輯在 rInflate():
void rInflate(XmlPullParser parser, View parent, Context context, 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();
...
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
遍歷體現在 while 迴圈上,name 為子節點名稱(如 TextView、RelativeLayout)。以 tag、include 等開頭的子節點走前面的 if 邏輯,而尋常 View 走 else:先呼叫同一個 createViewFromTag() 建立子 View,設定其 LayoutParams,接著遞迴呼叫 rInflateChildren() 處理該子節點下的所有 View,最後才把子節點加入父布局——這個父布局可能是根節點,也可能是某個子節點。遍歷結束後,所有子 View 都已加入布局並設定好相應的布局參數。
至此,LayoutInflater.from().inflate() 的源碼解析就完成了。理解這套「反射建立 + 遞迴遍歷」的機制,也就能明白 Android 是如何把一份靜態的 XML 布局,動態地還原成一棵 View 樹的。
Android 通訊錄實戰(三):短信讀取與發送的完整實現
在這個系列的前兩篇文章裡,我們已經分別談過如何取得手機裡的聯絡人以及通話紀錄。到了第三篇,終於要來啃最硬的一塊骨頭——短信。之所以說它是通訊管理中的難點,是因為短信同時牽
FrameLayout 搭配 Fragment:Android 主從式 UI 布局實作
把 Fragment 與 Layout 結合使用,通常是讓主 Activity 以 frame 填補的方式來管理 Fragment,形成左列表、右詳情的主從式版面。 1.
Android 圖片處理實例大全(圓角、濾鏡、模糊、素描、銳化)
圖片處理是 Android 開發中常見且實用的技能,無論是美化界面還是實現相機類應用,都離不開對 Bitmap 的操作。本文整理了幾種經典的圖片處理效果,並附上完整代碼,
安卓結合阿裡雲 OSS 實現視頻、音頻與圖片的上傳與下載
阿里雲 OSS 是什麼 阿里雲物件儲存服務 OSS 提供海量、安全、低成本的雲端儲存能力。開發者可透過 API 在任何時間、任何地點上傳與下載資料,也可以用來保存圖片、音