Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

InflateException: Error inflating class —— 自訂 View 忘了寫這個建構子

編輯:Android 開發實例

在 layout 檔案中使用自訂 View 時,遇到這樣的錯誤:

12-11 17:28:26.962: ERROR/AndroidRuntime(17121):
android.view.InflateException: Binary XML file line #6: Error inflating class
fish.apps.ipcall.controls.ColorableTextView

原因是沒有重載帶 AttributeSet 參數的建構子:

public ColorableTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

為什麼一定要這個建構子

當 LayoutInflater 從 XML 建立檢視時,它只認得 (Context, AttributeSet) 這個簽名——因為 XML 上寫的所有屬性(android:id、android:textSize 等)都要透過 AttributeSet 傳進來。少了它,反射找不到對應的建構子,就會在 inflate 階段直接拋出 InflateException。

實務上建議把三個建構子都寫齊,以涵蓋不同情境:

public ColorableTextView(Context context) {
    this(context, null);
}

public ColorableTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ColorableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    // 在這裡讀取自訂屬性
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorableTextView);
    // ...
    a.recycle();
}

其中 (Context) 用於純程式碼建立檢視;(Context, AttributeSet, int) 則是加上預設樣式的版本,也是讀取自訂屬性最合適的位置。若你的自訂 View 宣告在 XML 中卻只寫了 (Context),就會重現這個錯誤。

其他會造成類似症狀的原因

如果三個建構子都齊了還是報同樣的錯,往下列方向檢查:

  • 類別路徑寫錯。XML 中 <fish.apps.ipcall.controls.ColorableTextView> 必須是完整套件名稱,大小寫也要一致。
  • 內部類別要用 $ 而非 .若 View 定義為某類別的 static inner class,XML 中應寫成 com.example.Outer$InnerView。
  • 建構子拋出例外。例如在建構子中做了尚未初始化的資源讀取或依賴注入,例外會被包裝成 InflateException 往上拋。此時看 log 中 "Caused by" 之後的堆疊才是真正的根因。
  • 缺少 defStyleAttr 的樣式資源。自訂屬性忘了在 attrs.xml 中宣告 declare-styleable,也會在建構階段失敗。

一個快速定位技巧:把 log 過濾關鍵字設為 Caused by,AndroidRuntime 印出的第一段落往往只是外層包裝,真正的錯誤藏在後面。

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