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

Android 動態 inflate 佈局並獲取子 View:LayoutInflater 正確用法

     編輯:程式設計綜合問答

在代碼中動態加載 XML 佈局並查找子控件(如 ListView、ProgressBar),需使用 LayoutInflater.inflate() 獲取根 View,再對其調用 findViewById。

標準步驟

// 1. 獲取 LayoutInflater(Activity/Fragment/Context 均可)
LayoutInflater inflater = getLayoutInflater(); // 或 LayoutInflater.from(context)

// 2. inflate 佈局,attachToRoot 傳 false(手動添加到容器時)
View rootView = inflater.inflate(R.layout.your_layout_id, null);

// 3. 在 rootView 上查找子控件
ListView listView = rootView.findViewById(R.id.streamListView);
ProgressBar progressBar = rootView.findViewById(R.id.streamProgressBar);

// 4. 後續操作:添加到容器、設置數據等
container.addView(rootView);

關鍵參數說明

  • inflate(int resource, ViewGroup root, boolean attachToRoot):
    • root:用於生成 LayoutParams 的父容器,可傳 null。
    • attachToRoot:true 直接添加到 root;false 僅 inflate 返回 View,手動添加。
  • 若在 RecyclerView.Adapter 或 Fragment.onCreateView 中,通常傳 parent, false。

常見錯誤

// ❌ 錯誤:在 inflater 上直接 findViewById
ListView lv = inflater.findViewById(R.id.streamListView); // inflater 沒有此方法

// ✅ 正確:在 inflate 返回的 View 上查找
View v = inflater.inflate(...);
ListView lv = v.findViewById(...);

掌握 inflate 流程,動態佈局加載不再出錯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved