Programmatically build xml layout file
<p>I have an activity that lets users dynamically build layouts. It consists of a LinearLayout, a button to add a new LinearLayout and a button to save. Each time you click the button a new LinearLayout containing it's own button is created. Click that new button and a TextView is created inside that LinearLayout, etc.</p>

<p>I want users to be able to save and restore their layouts. So I'm thinking I can run through childviews and programmatically build an xml layout file, which I later setContentView(new.xml).</p>

<p>I'm using the guide <a href="http://www.anddev.org/write_a_simple_xml_file_in_the_sd_card_using_xmlserializer-t8350.html" rel="nofollow" title="here">here</a> to write an xml file to an sd card. And basically, when I create a new LinearLayout I setTag("LinearLayout"), new Button... setTag("Button"), etc... for the xml tags. Then I run through the following for loops to create the xml.</p>

<pre><code>for (int i = 2; i &lt; mainLayout.getChildCount(); i++) {
   serializer.startTag(null, mainLayout.getChildAt(i).getTag().toString());
   for (int b = 1; b &lt;= findViewById(mainLayout.getChildAt(i)).getChildCount(); b++) {
      serializer.startTag(null, findViewById(mainLayout.getChildAt(i)).getChildAt(b).getTag().toString());
      serializer.attribute(null, "android:text", findViewById(mainLayout.getChildAt(i)).getChildAt(b).getText().toString());
      serializer.endTag(null, findViewById(mainLayout.getChildAt(i)).getChildAt(b).getTag().toString());
   }
   serializer.endTag(null, mainLayout.getChildAt(i).getTag().toString());
}
</code></pre>

<p>If you add 1 LinearLayout and add 1 TextView to that LinearLayout, it should ouput:</p>

<pre><code>&lt;?xml version='1.0' encoding='UTF-8' standalone='yes' ?&gt;
&lt;LinearLayout&gt;
   &lt;LinearLayout&gt;
      &lt;TextView android:text="the text"&gt;&lt;/TextView&gt;
   &lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
</code></pre>

<p>This doesn't seem like the best way to be doing it however. I'm curious if anybody knows whether or not this will actually work or if there is a better way?</p>
