3

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!

AndroidPenguin
  • 3,445
  • 2
  • 21
  • 42

1 Answers1

5
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.

Squonk
  • 48,735
  • 19
  • 103
  • 135
  • 2
    The first solution resulted in no error but only one view being added. The second worked perfectly! :D – AndroidPenguin Dec 24 '12 at 20:02
  • @AndroidPenguin : Glad to help - I figured one of them would work but couldn't remember exactly as it's been a while since I did something like this. – Squonk Dec 24 '12 at 20:05
  • I can't believe it was that simple a solution, thought I must be completely off or something :P Really appreciate the help Squonk. :) – AndroidPenguin Dec 24 '12 at 20:07