文章轉自:http://blog.csdn.net/yaolingrui/article/details/7339913
在android開發過程中,有時會在不同情況下遇到同種問題:
- java.lang.IllegalStateException The specified child already has a parent. You must call removeView() on the child's parent first.
新建一個項目,佈局文件中僅包含一個TextView和一個ImageView,佈局方式是線性佈局(具體可以參考後面的源代碼),運行的結果就是顯示一個文本和一張圖片,
在Activity的onCreate()方法中,我們通常使用以下這種方式來使用佈局文件main.xml。
- setContentView(R.layout.main);
這裏爲了解釋今天要講解的這個異常,換一種佈局文件的使用方式,即把上面的那一行代碼註釋掉,換成以下代碼:
//獲取Infalter對象
- LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
- LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);
- ImageView child = (ImageView)parent.findViewById(R.id.child);
- setContentView(parent);
LayoutInflater爲佈局填充類,不明白的可以自己查,或者有機會我將在博客中介紹一下,然後是將main.xml文件inflate爲LinearLayout文件,再得到child,即ImageView。然後就是通過調用setContentView(parent)將這個佈局main.xml顯示出來,這時得到的效果和僅使用setContentView(R.layout.main)這句代碼得到的效果一樣。
下面的操作將會出現異常了,大家注意:
- setContentView(child);
而這時在異常中它提示要再parent中調用removeView()。這裏我們就聽從指揮,在setContentView(child),之前添上一句parent.removeView(child),這時就不會再調用setContentView(child)就不會異常了,當然當前顯示的將只是一幅圖片了,而這時如果你調用setContentView(parent)的話將只顯示文本內容,因爲我們已經將child remove掉了嘛。
代碼如下: