Reputation: 3453
For my app I have to dynamically create a number of horizontal linearlayouts with checkboxes and textviews. Currently I create these dynamically within a for loop. For performance and ease I thought using layoutinflater would be a better way to do this and thus define one horizontal linearlayout with the correct formatting then add these within some sort of a loop however I'm having trouble with this. I'm also open to if there are better ways to implement what I'm after (or if my current way is indeed better for performance etc.)
//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);
Problem is I can't put this in a for loop of any kind. Below is the error log for repeating the addView command.
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.
I've also considered adding the layout to the main linearlayout and then getting it and duplicating it and then adding more. Could you guys possibly help me learn how to do this?
Thank you very much!
Upvotes: 3
Views: 2498
Reputation: 48871
LinearLayout l = (LinearLayout) inflate.inflate(R.layout.inflater, main, false);
I suspect the problem is you are specifying main
as the ViewGroup
parameter.
Try setting the attachToRoot
parameter to true
then remove the main.addView(l)
line.
Alternatively set the ViewGroup
parameter to null
and keep the main.addView(l)
line.
Upvotes: 5