編輯:關於 Android 程式設計
在 Android 開發中,為了 inflate 一個布局檔,大致有兩種方式:
// 1. 取得 LayoutInflater 實例,然後做想做的事 LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // 2. 若你已經在某個 View 類別裡,直接呼叫 View 的靜態 inflate 方法 View.inflate(context, R.layout.xxx_xml, someViewGroup/null);
<!-- View.java -->
/**
* Inflate a view from an XML resource. This convenience method wraps the
* {@link LayoutInflater} class, which provides a full range of options for view inflation.
*/
public static View inflate(Context context, int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
<!-- LayoutInflater.java -->
/**
* Obtains the LayoutInflater from the given context.
*/
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;
}
由此可見,兩者最終都走到方式 1。View.inflate 只是個 helper 方法,幫你少敲幾行而已。
接著看 Context.getSystemService 的實作,直接跳到 ContextImpl.java:
/**
* Override this class when the system service constructor needs a ContextImpl.
* Else, use StaticServiceFetcher below.
*/
/*package*/ static class ServiceFetcher {
int mContextCacheIndex = -1;
/**
* Main entrypoint; only override if you don't need caching.
*/
public Object getService(ContextImpl ctx) {
ArrayList<Object> cache = ctx.mServiceCache;
Object service;
synchronized (cache) {
if (cache.size() == 0) {
// 首次存取時初始化 cache 向量
for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {
cache.add(null);
}
} else {
service = cache.get(mContextCacheIndex); // 先從 cache 找
if (service != null) {
return service; // 已存在則直接回傳
}
}
}
service = createService(ctx); // 否則建立並加入 cache,只會呼叫一次
cache.set(mContextCacheIndex, service);
return service;
}
}
/**
* Override this to create a new per-Context instance of the service.
* getService() will handle locking and caching.
*/
public Object createService(ContextImpl ctx) {
throw new RuntimeException("Not implemented");
}
這裡有兩個值得注意的設計:
第一,快取是 per-Context 的。每個 ContextImpl 都有一個 mServiceCache,同一個 Context 內重複呼叫 getSystemService(LAYOUT_INFLATER_SERVICE) 會拿到同一個物件。這解釋了為什麼 LayoutInflater 可以安全地反覆使用。
第二,synchronized (cache) 只保護 cache 的讀寫。真正耗時的 createService() 是在同步區塊之外呼叫的,這是為了避免長時間鎖住 cache 影響效能;代價是在多執行緒同時首次存取時,可能短暫建立兩個實例,但最終只有一個會被寫進 cache。
/**
* Override this class for services to be cached process-wide.
*/
abstract static class StaticServiceFetcher extends ServiceFetcher {
private Object mCachedInstance;
@Override
public final Object getService(ContextImpl unused) {
synchronized (StaticServiceFetcher.this) {
Object service = mCachedInstance;
if (service != null) {
return service;
}
return mCachedInstance = createStaticService();
}
}
public abstract Object createStaticService(); // 不需要 ContextImpl 參數
}
StaticServiceFetcher 則是另一種層級:它讓服務在整個行程中只被建立一次,全域共用。兩者的差別在於「快取的粒度」——前者是每個 Context 一份,後者是每個行程一份。
private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
new HashMap<String, ServiceFetcher>(); // 全域 system service 的 map
private static int sNextPerContextServiceCacheIndex = 0;
private static void registerService(String serviceName, ServiceFetcher fetcher) {
if (!(fetcher instanceof StaticServiceFetcher)) {
fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
}
SYSTEM_SERVICE_MAP.put(serviceName, fetcher); // 放到全域的靜態 map 中
}
// 還有許多 registerService 呼叫,這裡只關注 LAYOUT_INFLATER_SERVICE
registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
public Object createService(ContextImpl ctx) {
// 回傳 PolicyManager.makeNewLayoutInflater(ctx.getOuterContext()),
// 實際上是 PhoneLayoutInflater 的物件
return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
}
});
到這裡就清楚了:getSystemService 只是從 SYSTEM_SERVICE_MAP 撈出對應的 ServiceFetcher,再交給它去 cache 找或建立。而 LayoutInflater 的實例,透過 PolicyManager.makeNewLayoutInflater() 建立的其實是 PhoneLayoutInflater——這個子類別覆寫了 onCreateView,用來支援 AppCompat 的元件替換機制。
public View inflate(int resource, ViewGroup root) {
// 實際上呼叫 3 個參數的版本。由此可見客戶端程式碼
// 沒必要寫 inflate(resource, root, root != null),直接這樣就好
return inflate(resource, root, root != null);
}
public View inflate(XmlPullParser parser, ViewGroup root) {
// 不太常用,我們一般用 layout 檔的版本,但實質都一樣
return inflate(parser, root, root != null);
// 下面的程式碼中 inflate 一個 include tag 時呼叫了此版本
}
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
注意 inflate(resource, root) 裡那句 root != null:它把「root 是否為 null」直接當成 attachToRoot 的值。這是一個容易誤解的地方——如果你傳了 root 但不想 attach,就必須明確使用三參數版本並傳 false。
這是最終會被呼叫的版本,也是整個流程的關鍵:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) { // 進入同步塊
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root; // 回傳值初始化為傳入的 root
try {
// 尋找根節點
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
// Empty
}
// 能走到這裡,說明 type 是 START_TAG 或 END_DOCUMENT
if (type != XmlPullParser.START_TAG) {
// 若一開始就是 END_DOCUMENT,說明 xml 檔有問題
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
// 能到這裡,type 一定是 START_TAG,也就是 xml 檔裡的 root node
final String name = parser.getName();
if (TAG_MERGE.equals(name)) {
// 處理 merge tag 的情況
if (root == null || !attachToRoot) {
// root 必須非空且 attachToRoot 為 true,否則拋異常
// 因為 merge 的 xml 並不代表某個具體的 view,
// 只是把它包起來的內容加到某個上層 ViewGroup 中
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, attrs, false); // 遞歸的 inflate
} else {
// Temp 是 xml 檔中找到的 root view
View temp;
if (TAG_1995.equals(name)) {
temp = new BlinkLayout(mContext, attrs);
} else {
temp = createViewFromTag(root, name, attrs); // 依 tag 節點建立 view
}
ViewGroup.LayoutParams params = null;
if (root != null) {
// 建立與 root 匹配的 LayoutParams
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// 若不 attach,就呼叫 view 的 setLayoutParams
// (若會 attach,則改用下面的 addView)
temp.setLayoutParams(params);
}
}
// 遞歸 inflate temp 底下所有的 children
rInflate(parser, temp, attrs, true);
// 把找到的所有 view attach 到 root 上
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 決定要回傳傳入的 root,還是 xml 中發現的 root view
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription() + ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
1. 為什麼要 synchronized (mConstructorArgs)?因為 mConstructorArgs 是 LayoutInflater 的成員陣列,後續 createView() 會用反射呼叫 View 的建構子,而建構子需要 Context 與 AttributeSet 兩個參數——它們就是透過這個共用陣列傳遞的。既然是可變的共用狀態,就必須鎖住,否則同一個 Inflater 被多執行緒使用時會傳錯參數。這也解釋了為什麼 LayoutInflater 不是 thread-safe 的。
2. result 的返回值邏輯。當 root != null && attachToRoot 時,回傳的是傳進來的 root;否則回傳 xml 中解析出的 temp。這正是 inflate(inflater_id, container, false) 在 Fragment 的 onCreateView 中能正常運作的原因——container 只被用來產生正確的 LayoutParams,不會被真的附加。
3. finally 中把 mConstructorArgs[0] 還原。這是為了「Don't retain static reference on context」——避免 LayoutInflater 長期持有 Activity 的 Context 參考而造成記憶體洩漏。這行清理很容易被忽略,卻是 framework 開發者刻意留下的防護。
/**
* 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;
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(); // 取得 tagName
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent); // 處理 REQUEST_FOCUS tag
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
// include 節點不能是根節點
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, parent, attrs); // 處理 include tag
} else if (TAG_MERGE.equals(name)) {
// merge 節點必須是 xml 檔裡的根節點,
// 也就是說走到這裡時不應該再出現 merge 節點
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 {
// 一般情況:各種 Android view、widget 或用戶自訂的 view 節點
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(); // 所有孩子都 inflate 完畢後的回呼
}
這裡有一個很值得留意的設計:深度優先且「先遞歸、後 addView」。也就是說,父 View 的所有子節點都建立並遞歸處理完之後,才把自己加進父容器,最後才呼叫 parent.onFinishInflate()。這保證了你在 onFinishInflate() 裡呼叫 findViewById() 時,整棵子樹都已經存在——這正是自訂 View 合併元件時的正確初始化時機。
View createViewFromTag(View parent, String name, AttributeSet attrs) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
if (DEBUG) System.out.println("******** Creating view: " + name);
try {
View view;
// 這裡我們忽略了各種 factory 的 onCreateView,有興趣的讀者可自行研究
if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs);
else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs);
else view = null;
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
}
if (view == null) {
if (-1 == name.indexOf('.')) {
// 建立 android.view.* 裡的任何 view,如 TextView、ImageView 等
view = onCreateView(parent, name, attrs);
// 其子類別 PhoneLayoutInflater 覆寫了此方法用來支援 AppCompat
} else {
// 建立 android.widget.* / android.webkit.* 裡的任何物件
// 以及用戶自訂的各種 View(如 com.xiaoweiz.browser.MyCustomView)
view = createView(name, null, attrs);
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
}
這裡的 「name 中有沒有點號」判斷是個巧妙的設計:沒有點號就補上 android.view. 前綴(走 onCreateView),有點號就直接當完整類別名稱載入。這解釋了為什麼布局檔裡寫 <TextView> 可以,寫 <view class="android.widget.TextView" /> 也可以,而自訂 View 則必須寫完整的 package 路徑。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 用戶自訂的 view 不需要 prefix,因為 name 中已經有所有需要的資訊;
// 系統的 prefix 則是 android.view. / android.widget. / android.webkit.
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// 快取中沒有,確認它是真的類別並嘗試加入
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
sConstructorMap.put(name, constructor); // 放進靜態快取
} else {
// 若已有快取,仍要套用 filter
if (mFilter != null) {
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// 新類別 —— 記住它是否被允許
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs; // 需要 Context 與 AttributeSet 兩個參數的版本
args[1] = attrs;
// 如果你不打算動態 inflate 你的 view,則沒必要提供此版本的 ctor。
final View view = constructor.newInstance(args); // 建立 View 實例
if (view instanceof ViewStub) {
// ViewStub 的特殊處理:之後 inflate ViewStub 時一律用我們自己
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(this);
}
return view;
} catch (NoSuchMethodException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassCastException e) {
// 載入的類別不是 View 的子類
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View " + (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassNotFoundException e) {
throw e; // loadClass 失敗時直接往外拋
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()));
ie.initCause(e);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
1. sConstructorMap 是全域靜態快取。它快取的是 Constructor 而非 Class,因為 loadClass() 與 getConstructor() 都是相對慢的操作,而 inflate 在列表滾動時可能被呼叫數百次。這個靜態快取是效能的關鍵。
2. mConstructorSignature 固定為 {Context.class, AttributeSet.class}。也就是說,任何要出現在布局檔中的 View,都必須提供 (Context, AttributeSet) 這個建構子,否則會拋 NoSuchMethodException。這是自訂 View 最常犯的錯誤——只寫了 (Context) 建構子,在預覽畫面正常但執行時崩潰。
3. asSubclass(View.class) 與 ClassCastException 的處理。前者在載入時就驗證型別,後者處理「類別存在但不是 View 子類」的情況。兩者合起來保證了 inflate 出來的一定是 View。
把整條鏈路串起來:
getSystemService(LAYOUT_INFLATER_SERVICE) → 從 SYSTEM_SERVICE_MAP 取得 ServiceFetcher → 從 per-Context 的 mServiceCache 回傳(或建立)PhoneLayoutInflater → inflate(resource, root, attachToRoot) → 取得 XmlResourceParser → 解析根節點 → createViewFromTag 判斷是否為特殊 tag(merge/include/blink)→ createView 走反射建立 View → rInflate 深度優先遞歸處理所有子節點 → addView 組裝成樹 → onFinishInflate 回呼。
理解這條鏈路之後,幾個常見現象就有了解釋:為什麼自訂 View 一定要寫 (Context, AttributeSet) 建構子;為什麼 <merge> 一定要搭配 ViewGroup root 與 attachToRoot=true;為什麼 <include> 不能當根節點;以及為什麼在 onFinishInflate() 裡 findViewById() 是安全的,而在 onStart() 裡卻可能拿不到尺寸。
Android ViewGroup 觸摸事件攔截完全解析
前言在自定義 ViewGroup 的開發過程中,觸摸事件的攔截幾乎是繞不開的一環。最典型的例子莫過於 ListView 的下拉刷新——手指下滑時,列表並不把事件交給子項,
重寫 ViewPager 調整滑動靈敏度:滑動距離不足則停留原頁
用 ViewPager 做頁面切換很方便,一個容器裡能塞任意多個 View。但它有個惱人的特性:太靈敏。用戶在頁面內部操作時——比如點擊一個列表項、拖動一個小控件——手指
OSGi ServiceListener實戰:動態監聽服務註冊與變更
前言 在OSGi的世界裡,動態性是最鮮明的特徵之一。Bundle可以在執行期安裝、啟動、停止、更新與移除,而服務也可能隨時被註冊、修改或取消註冊。若應用需要即時感知這些變
Android 用 GridView 打造完整日曆元件(附完整程式碼)
自製日曆是很能磨基本功的題目,牽涉到日期推算、閏年判斷、農曆轉換與手勢翻頁。先看一眼成果: 一、主版面配置 上方是月份切換列,中間是星期標頭,下方用 7 欄的 Gri