2012-12-15 48 views
16

我想用XML創建UI佈局,並將其作爲子視圖插入現有視圖(它將被插入多次)。在Android上使用XML以編程方式創建視圖

例如,這裏是XML文件將包含:

<RelativeLayout 
    android:id="@+id/relativeLayout1" > 
    <Button android:id="@+id/myButton" 
     android:text="@string/mystring" /> 
</RelativeLayout> 

現在,我得到了父母的LinearLayout現在想的是XML文件添加爲子視圖,如:

LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout); 
//need to create a view object from the xml file 
linear.addView(myXmlObject); 

是否可以將XML資源轉換爲視圖類型?如果是這樣,我將如何做到這一點?

+1

@Eric哦,哇,我錯過了。可是等等! – Sam

+1

@Sam我怎麼......我只是......好吧,你完全擁有我在那裏。 – Eric

+0

感覺像我這樣的人,你應該找某種適配器。 – FoamyGuy

回答

61

我相信你想LayoutInflater。假設您的示例XML位於文件中custom_layout.xml

LayoutInflater inflater = LayoutInflater.from(context); 
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_layout, null, false); 

LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout); 
linear.addView(layout); 
+0

謝謝老兄。你節省了我的時間 –

+0

你是如何處理按鈕點擊的?我的意思是每行的按鈕點擊具有不同的功能。 – user4057066

相關問題