關於異常“The specified child already has a parent. You must call removeView"的解決(舉例說明,附源碼)

文章轉自:http://blog.csdn.net/yaolingrui/article/details/7339913

android開發過程中,有時會在不同情況下遇到同種問題:

[java] view plaincopy
  1. java.lang.IllegalStateException The specified child already has a parent. You must call removeView() on the child's parent first.  
也就是非法狀態異常,它說這個特定的child已經有一個parent了,你必須在這個parent中首先調用removeView()方法,才能繼續你的內容。這裏很明顯這個child是一個View,一個子(childView必須依賴於父(parentView,如果你要使用這個child,則必須通過parent,而你如果就是硬想使用這個child,那麼就得讓這個childparent脫離父子關係(即removeView())……算了還是舉個簡單的例子來說明一下,省的我說的亂七八糟,你聽的也暈。

新建一個項目,佈局文件中僅包含一個TextView和一個ImageView,佈局方式是線性佈局(具體可以參考後面的源代碼),運行的結果就是顯示一個文本和一張圖片,

ActivityonCreate()方法中,我們通常使用以下這種方式來使用佈局文件main.xml

[java] view plaincopy
  1. setContentView(R.layout.main);  

這裏爲了解釋今天要講解的這個異常,換一種佈局文件的使用方式,即把上面的那一行代碼註釋掉,換成以下代碼:

//獲取Infalter對象

[java] view plaincopy
  1. LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  
  2. LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);  
  3. ImageView child = (ImageView)parent.findViewById(R.id.child);          
  4. setContentView(parent);  

LayoutInflater爲佈局填充類,不明白的可以自己查,或者有機會我將在博客中介紹一下,然後是將main.xml文件inflateLinearLayout文件,再得到child,即ImageView。然後就是通過調用setContentView(parent)將這個佈局main.xml顯示出來,這時得到的效果和僅使用setContentView(R.layout.main)這句代碼得到的效果一樣。

下面的操作將會出現異常了,大家注意:

[java] view plaincopy
  1. setContentView(child);  
也就是將上文setContentView(parent),中的parent換成child。異常請看如下截圖:


而這時在異常中它提示要再parent中調用removeView()。這裏我們就聽從指揮,在setContentView(child),之前添上一句parent.removeView(child),這時就不會再調用setContentView(child)就不會異常了,當然當前顯示的將只是一幅圖片了,而這時如果你調用setContentView(parent)的話將只顯示文本內容,因爲我們已經將child remove掉了嘛。

代碼如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章