开发者

Programmatically build xml layout file

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.

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

I'm using the guide here 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.

for (int i = 2; i < mainLayout.getChildCount(); i++) {
   serializer.startTag(null, mainLayout.getChildAt(i).getTag().toString());
   for (int b = 1; b <= 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());
}

If you add 1 LinearLayout and add 1 TextView to that LinearLayout, it should ouput:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<LinearLayout>
   <LinearLayout>
      <TextVi开发者_StackOverflow社区ew android:text="the text"></TextView>
   </LinearLayout>
</LinearLayout>

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?


there exists a method to inflate layouts from an xmlpullparser http://developer.android.com/reference/android/view/LayoutInflater.html#inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup)

but

view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime.

so when you write the xml file to the memory card, it can not be inflated through http://developer.android.com/reference/android/view/LayoutInflater.html#inflate(int, android.view.ViewGroup)

which requires the xml file to be pre-processed and packaged in the apk.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜