2012-12-24 55 views
3

對於我的應用程序,我必須動態創建與複選框和textviews的水平linearlayouts數量。目前我在for循環內動態創建這些。爲了性能和易用性,我認爲使用layoutinflater會是一種更好的方式來實現這一點,因此定義一個具有正確格式的水平線性佈局,然後在某種循環內添加這些佈局,但是我遇到了這個問題。我也開到是否有實現的東西我以後是更好的方式(或者,如果我現在的路確實是更好的性能等)LayoutInflater添加多個視圖

//my main layout 
LinearLayout main = (LinearLayout) findViewById(R.id.main); 
LayoutInflater inflate = getLayoutInflater(); 
//inflating the layout containing the horizontal 
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false); 
//adding the view 
main.addView(l); 

問題是我不能把這個在一對任何類型的循環。以下是重複addView命令的錯誤日誌。

12-24 19:37:18.668: E/AndroidRuntime(8780): java.lang.RuntimeException: Unable 
to start activity ComponentInfo{com.example.test1/com.example.test1.MainActivity}: 
java.lang.IllegalStateException: The specified child already has a 
parent. You must call removeView() on the child's parent first. 

我也考慮加入佈局,主要的LinearLayout,然後得到它,複製它,然後添加更多。你們能否幫我學習如何做到這一點?

非常感謝!

+0

爲什麼你不能把它放在任何類型的循環中? –

+0

對不起,我已經包含了我的logcat。 – AndroidPenguin

+0

如果您在循環中設置線性佈局的ID,即l.setId(i) – jnthnjns

回答

5
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false); 

我懷疑問題是您指定main作爲ViewGroup參數。

嘗試將attachToRoot參數設置爲true,然後刪除main.addView(l)行。

或者將ViewGroup參數設置爲null並保留main.addView(l)一行。

+2

第一個解決方案導致沒有錯誤,但只添加了一個視圖。第二個完美的工作! :D – AndroidPenguin

+0

@AndroidPenguin:很高興幫助 - 我想他們中的一個會工作,但不能完全記得,因爲我做了這樣的事情已經有一段時間了。 – Squonk

+0

我不能相信這是一個簡單的解決方案,我認爲我必須徹底關閉或什麼:P真的很感謝Squonk的幫助。 :) – AndroidPenguin