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

Android 標籤 findViewById 為 null:必須給被 include 佈局根元素指定 id

     編輯:程式設計疑難解答

現象:`` 後在 Java/Kotlin `findViewById(R.id.xxx)` 取不到 View,拋 `NullPointerException`。

原因:`` 本身不產生 View 節點,直接將子佈局根元素「提升」到父佈局層級

  • 若子佈局根元素 **已有 `android:id`**,提升後該 id 歸屬於提升後的 View,**可直接 `findViewById`**。
  • 若子佈局根元素 **無 `android:id`**,提升後該 View **無 id**,無法透過 `findViewById` 取得,只能遍歷父佈局 `getChildAt` 找。

正確寫法




    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    




    
    

Java/Kotlin 取得多個 include 實例


// 因為 id 相同,findViewById 只會回傳第一個
View first = findViewById(R.id.item_root);

// 取得所有:遍歷父容器
ViewGroup parent = findViewById(R.id.parent_container);
for (int i = 0; i < parent.getChildCount(); i++) {
    View child = parent.getChildAt(i);
    if (child.getId() == R.id.item_root) {
        TextView tv = child.findViewById(R.id.item_text);
        // 對每個 include 實例操作
    }
}

// 或用 ViewBinding (推薦)
val binding = ActivityMainBinding.inflate(layoutInflater)
binding.itemRoot.text = "第一個" // 自動對應第一個 include
// 其餘需手動遍歷

最佳實踐

  1. **子佈局根元素一定要加 `android:id`**,否則無法精準定位。
  2. 同一佈局多次 `` 時,**id 會重複**,`findViewById` 只回傳第一個,**改用 ViewBinding + 遍歷父容器**。
  3. 若需區分每個 include,外層包一層 `` 或給 `` 加 `android:id` (API 26+ 支援),但根元素 id 仍是核心。

記住:**include 不產生 View,根元素 id 才是定位鍵**,加上 id 再用 ViewBinding,`NullPointerException` 徹底消失。

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