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

在 XML 中引用自訂內部類 View:四個「為什麼」背後的源碼真相

編輯:關於 Android 程式設計

最近在 XML 裡使用以「內部類」形式定義的自訂 View,踩了不少坑。網上文章給出了做法,卻大多沒說清楚「為什麼必須這樣寫」。既然要弄懂,就從 LayoutInflater 的源碼一路追到底吧。

先給結論:四條規則

  1. 自訂的類必須是靜態類(static)。
  2. 標籤名稱使用 view,注意是小寫的 v。
  3. 加上 class 屬性(不帶 android: 命名空間),內容為完整類路徑,外部類與內部類之間用美元符號 $ 連接,而不是點。
  4. 必須至少有一個同時接受 Context 與 AttributeSet 兩個參數的建構子。

版面載入流程的關鍵程式碼

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」開始。

① 為什麼 class 屬性要用 $ 連接?

在「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.

這段話一次解釋了兩件事:

  1. 建構子必須與傳入的參數型別完全匹配,否則丟出 NoSuchMethodException。所以自訂 View 一定要有一個 (Context, AttributeSet) 的建構子。
  2. 若該類是非靜態內部類,簽章中的第一個參數會是「外部類實例」。而程式碼傳入的 mConstructorSignature 並沒有這個參數,因此非靜態內部類一定會出錯。

有些人只解釋成「非靜態內部類需要外部類實例來引用」,但萬一系統在載入時自動補上一個外部類實例呢?這裡的源碼給了明確的否定答案。

③ 為什麼 newInstance 也要求靜態?

取得 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 必須宣告為靜態。

④ 為什麼可以直接寫 <Button />?

若 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 標籤會發生什麼事?

如果不用 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。

總結:三種正確的引用途徑

  1. 只用簡單類名 <ViewName />:僅適用於 android.widget、android.webkit、android.app、android.view 這四個套件下的類,因為系統會自動補上前綴。
  2. 使用完整類名 <com.willhua.MyView />:任何非內部類的 View 都可以這樣寫,但內部類不行,因為不符合 Java 的命名規範。
  3. 使用 view + class 屬性 <view class="完整類名" />:最通用的方式,所有類別都能這樣引用,唯一前提是類名要寫對(內部類记得用 $ 連接)。

為了搞懂一個內部類載入的問題,反而把整個 inflate 流程都摸清楚了,收穫比預期多得多。

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