編輯:關於 Android 程式設計
最近在 XML 裡使用以「內部類」形式定義的自訂 View,踩了不少坑。網上文章給出了做法,卻大多沒說清楚「為什麼必須這樣寫」。既然要弄懂,就從 LayoutInflater 的源碼一路追到底吧。
class 屬性(不帶 android: 命名空間),內容為完整類路徑,外部類與內部類之間用美元符號 $ 連接,而不是點。XML 版面一律由 LayoutInflater 負責載入,實際使用的實作是其子類 PhoneLayoutInflater。真正把 View 具現化的入口是 createViewFromTag(),再由 createView() 完成實例化。
final Object[] mConstructorArgs = new Object[2];
static final Class<?>[] mConstructorSignature = new Class[] { Context.class, AttributeSet.class };
/**
* Creates a view from a tag name using the supplied attribute set.
*/
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
//**關鍵 1**//
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
//**關鍵 2**//
view = onCreateView(parent, name, attrs);
} else {
//**關鍵 3**//
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
}
// 後續為 catch 區塊,此處省略
}
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
return onCreateView(name, attrs);
}
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
/**
* Low-level function for instantiating a view by name.
*/
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 {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
//**關鍵 4**//
// 快取中沒有,確認類別存在並加入快取
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);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
// 已快取時只額外做 mFilter 的合法性判斷,不影響載入流程
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;
args[1] = attrs;
//**關鍵 5**//
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// ViewStub 之後 inflate 時沿用同一個 Context
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
}
// 後續為 catch 與 finally,此處省略
}
PhoneLayoutInflater 中相關的部分:
public class PhoneLayoutInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
/**
* Override onCreateView to instantiate names that correspond to the widgets
* known to the Widget factory. If we don't find a match, call through to our super class.
*/
@Override
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
//**關鍵 6**//
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// 交給父類再試一次
}
}
return super.onCreateView(name, attrs);
}
}
以下用「1」代表程式碼中標示「關鍵 1」的位置,依此類推。任何 XML 元素都從「1」開始。
在「1」處,程式判斷標籤名是否為 view。若成立,name 會被改寫成 class 屬性的值,例如 com.willhua.view.MyView 或 com.willhua.view.MyClass$MyView——這也正是必須用 view 當標籤名的理由。
由於 name 中含有「.」,流程走到「3」,呼叫 createView(name, null, attrs),prefix 為 null。到了「4」,loadClass() 的參數就直接是 name,也就是 class 屬性的值。而 Java 的規範中,內部類的完整類名正是「外部類名 + $ + 內部類名」,所以答案是:為了符合 JVM 的類命名規則。(第一次載入時建構子必然不存在於快取,所以走 if 分支;之後再載入則走 else,但那裡只做過濾判斷,不影響本質流程。)
「4」處有個關鍵句子:
constructor = clazz.getConstructor(mConstructorSignature);
而 mConstructorSignature 的定義是:
static final Class<?>[] mConstructorSignature = new Class[] { Context.class, AttributeSet.class };
查 Oracle 對 getConstructor 的說明:
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
這段話一次解釋了兩件事:
NoSuchMethodException。所以自訂 View 一定要有一個 (Context, AttributeSet) 的建構子。有些人只解釋成「非靜態內部類需要外部類實例來引用」,但萬一系統在載入時自動補上一個外部類實例呢?這裡的源碼給了明確的否定答案。
取得 clazz 後流程來到「5」。前面提過 mConstructorArgs 是 Object[2],且 mConstructorArgs[0] 在建構 LayoutInflater 時就被賦值為 context。所以傳給 newInstance 的參數就是 Context 與 AttributeSet。
Oracle 對 newInstance 的說明也有一句:
If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance.
我們同樣沒有傳入外部類實例,所以再次印證:自訂內部類 View 必須宣告為靜態。
若 name 中不含「.」,流程走「2」:onCreateView(parent, name, attrs) → onCreateView(name, attrs) → createView(name, "android.view.", attrs)。
而實際使用的 PhoneLayoutInflater 覆寫了 onCreateView(name, attrs),也就是「6」處:它會依序嘗試 android.widget.、android.webkit.、android.app. 三個前綴,都找不到才回退到父類加上 android.view.。這就是為什麼 <Button />、<View /> 這些常用控制項可以只寫簡短名稱。
如果不用 view 標籤,XML 中就只能寫 <com.willhua.MyClass.MyView />,而不能寫 <com.willhua.MyClass$MyView />(Android Studio 會直接報 "Tag start is not close")。而寫成點的形式時,「4」處會去載入 com.willhua.MyClass.MyView,這不符合 Java 內部類的命名規則,執行期必然失敗。
另外常見的手誤是把 v 寫成大寫,變成 <View class="com.willhua.MyClass$MyView" ... />,結果會在執行期報型別錯誤——因為你實際定義的是 android.view.View,程式碼卻當它是 com.willhua.MyClass$MyView。
<ViewName />:僅適用於 android.widget、android.webkit、android.app、android.view 這四個套件下的類,因為系統會自動補上前綴。<com.willhua.MyView />:任何非內部類的 View 都可以這樣寫,但內部類不行,因為不符合 Java 的命名規範。<view class="完整類名" />:最通用的方式,所有類別都能這樣引用,唯一前提是類名要寫對(內部類记得用 $ 連接)。為了搞懂一個內部類載入的問題,反而把整個 inflate 流程都摸清楚了,收穫比預期多得多。
Android Studio 中使用 JNI 與 NDK 的完整步驟
這是我第一次寫部落格,請多指教。初次接觸 Android NDK 時我完全一頭霧水,因為專案需要與 Bluetooth 下位機溝通,必須在應用裡嵌入 C++ 演算法。折騰
Android 平台 Camera 實時濾鏡實作探討(八):一個簡單的美顏濾鏡
美顏通常包含磨皮、美白、瘦臉等效果,其中磨皮演算法的討論已經很多,例如雙指數邊緣平滑濾波器、選擇性模糊、基於局部均方差相關資訊的圖像去噪、導向濾波磨皮、遞歸雙邊濾波磨皮等
Android ListView 實作下拉刷新與上拉加載更多
本文為大家介紹 Android ListView 下拉刷新與上拉加載更多的實作方法,供大家參考。 一、ListView 優化方式 介面緩存:ViewHolder + co
Android 相機開發:系統相機、自定義相機與大圖加載優化
本篇文章介紹 Android 上實現拍照並顯示的兩種方式——調用系統相機與自定義相機介面,同時會涉及一個繞不開的問題:如何正確地把高解析度照片加載到內存中而不引發 OOM