2011-04-27 49 views
0

我有一個允許用戶動態構建佈局的活動。它由一個LinearLayout,一個添加一個新的LinearLayout和一個按鈕來保存的按鈕組成。每次單擊該按鈕時,都會創建一個包含它自己的按鈕的新LinearLayout。單擊該新按鈕並在該LinearLayout內創建TextView等。以編程方式構建xml佈局文件

我希望用戶能夠保存和恢復其佈局。所以我想我可以通過childviews運行,並編程建立一個XML佈局文件,我後來setContentView(new.xml)。

我正在使用指南here將xml文件寫入SD卡。基本上,當我爲xml標籤創建一個新的LinearLayout I setTag(「LinearLayout」),新的Button ... setTag(「Button」)等等。然後我運行以下for循環來創建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()); 
} 

如果你加1周的LinearLayout,並添加1周的TextView到的LinearLayout,它應該輸出繼電器:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?> 
<LinearLayout> 
    <LinearLayout> 
     <TextView android:text="the text"></TextView> 
    </LinearLayout> 
</LinearLayout> 

這似乎不是最好的辦法然而,可以這樣做。我很好奇,如果有人知道這是否會實際工作,或者如果有更好的方法?

回答

1

存在於從xmlpullparser http://developer.android.com/reference/android/view/LayoutInflater.html#inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup)

視圖通貨膨脹在很大程度上依賴於是 在生成時進行的XML文件 預處理膨脹佈局的方法。因此, 目前無法在運行時通過普通XML文件使用 LayoutInflater和XmlPullParser 。

所以當你寫xml文件到存儲器卡,它可以不通過 http://developer.android.com/reference/android/view/LayoutInflater.html#inflate(int, android.view.ViewGroup)

這需要被預加工和包裝在APK xml文件膨脹。