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

Android錯誤:The specified child already has a parent. 解法

編輯:Android 開發教學

在Android開發中,若使用FragmentActivity與Fragment,並在onCreateView中使用inflate,可能會遇到「The specified child already has a parent」例外。這個錯誤通常代表某個View已經有父容器,卻又被嘗試加入新的父容器。

常見原因

典型寫法如下:

View v = inflater.inflate(R.layout.preference_fragment, container);

當container不為null時,inflate可能會直接把新View加入container。若該View已有父物件,就會拋出例外。

解決方式

可將inflate的第三個參數設為false:

View v = inflater.inflate(R.layout.preference_fragment, container, false);

這樣只會建立View,而不會自動附加到container,再由Fragment或Activity決定何時加入。

補充

這個錯誤不一定只由上述原因造成,也可能是View被重複add、removeView順序錯誤或自訂ViewGroup操作不當。建議檢查所有 dynamically added views 的生命週期,確保每個子View只有一個父容器。

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