在代碼中動態加載 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 流程,動態佈局加載不再出錯。