對於我的應用程序,我必須動態創建與複選框和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,然後得到它,複製它,然後添加更多。你們能否幫我學習如何做到這一點?
非常感謝!
爲什麼你不能把它放在任何類型的循環中? –
對不起,我已經包含了我的logcat。 – AndroidPenguin
如果您在循環中設置線性佈局的ID,即l.setId(i) – jnthnjns