首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android LayoutInflater 載入自定義 View 失敗的解決方案

     編輯:程式設計綜合問答

問題現象

使用 LayoutInflater.inflate() 載入包含自定義 View 的布局檔時,拋出 RuntimeException,提示缺少 R.id.panelHandle 的子 View。

原因分析

自定義 View 類別(如 SlidingDrawer 等)在 XML 中宣告時,若指定了特定屬性(如 handle),則布局內必須存在對應 ID 的子 View。缺少該 ID 會導致解析失敗。

解決方法

確保 XML 布局中包含自定義 View 所需的所有子元素及正確 ID。範例修正如下:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:panel="https://schemas.android.com/apk/res/com.alpha"
    android:id="@+id/layoutMain"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="top|right">
    <!-- 此處需添加 id 為 panelHandle 的子 View -->
    <View android:id="@+id/panelHandle" ... />
</RelativeLayout>

程式碼範例

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.app_layout, null);

注意事項

  • 檢查自定義 View 文檔,確認必要的屬性與子 View。
  • 使用 inflate(layoutRes, parent, false) 並手動 addView 可避免部分 LayoutParams 問題。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved