現象:`
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
// 因為 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
// 其餘需手動遍歷
記住:**include 不產生 View,根元素 id 才是定位鍵**,加上 id 再用 ViewBinding,`NullPointerException` 徹底消失。