Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ListView 出現「The specified child already has a parent」的原因與解法

編輯:關於 Android 程式設計

在 Android 的 ListView 開發中,若於 getView 裡把外部傳入的 Poker 控制項直接加入 convertView,上下滑動時很容易看到「The specified child already has a parent」的錯誤。這類問題通常不是單純的版面配置錯誤,而是 View 的父子關係被重複使用所造成。

問題核心

ListView 會重用 convertView,而原本的程式把 Poker 物件本身當成可加入的 View,並在每次 getView 時呼叫 addView。當同一個 Poker View 已經被加入某個 convertView,又被另一個 convertView 引用時,系統就會認為這個子 View 已經有父容器,於是抛出錯誤。

常見解法

  • 不要在資料模型裡長期持有 View,資料與 View 應分離。
  • 若需要動態加入子 View,先確認該 View 是否已有 parent,必要時先 removeView 或重新建立。
  • 善用 ViewHolder 模式,只在 convertView 為空時建立一次版面,避免重複 addView。
  • 若自行快取 convertView,也要避免讓同一個子 View 同時被多個位置共用。

總之,這個錯誤的本質是 View 只能有一個父容器。只要確保每個加入的 View 都來自新的實例,或在重用前先解除舊的父子關係,問題就能避免。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved