2010-03-09 13 views
1

對不起Newb-ness。Android:(Newb Question)基於xml編程創建視圖

我想創建一個LinearLayout(垂直)的視圖元素列表。我創建了一個XML的佈局,是一個名爲「category_list.xml」

<TableLayout> 
    <TableRow> 
    <ImageView /> 
    <TextView /> 
    <CheckBox /> 
    </TableRow> 
</TableLayout> 

我想要遍歷數組TableLayout,在每次迭代創建一個新的TableLayout視圖,並把它添加到的LinearLayout。我錯過的peice是基於上面的xml創建一個新的TableLayout。

TableLayout t = new TableLayout(R.layout.category_list); 

東西有人能指出我在正確的方向?以編程方式生成TableLayout更好嗎?

回答

3

或使用靜態View.inflate功能

TableLAyout t = (TableLayout) View.inflate(this, R.layout.category_list, null); 

總之,要小心有充氣和刪除太多視圖在你的應用程序中,因爲短暫的對象會泄漏內存。考慮使用帶有和Adapter的ListView。

+0

我最初想使用ListView,但我的印象是使用ListView時,活動需要擴展ListActivity,我不能這樣做,因爲它已經在擴展MapActivity。 – karnage 2010-03-09 20:49:42

2

您想要使用LayoutInflater來「膨脹」xml文件。您可以使用getLayoutInflater()獲得LayoutInflater的活動。下面是它如何工作的(假設你的LinearLayout的ID爲「父」):

LinearLayout parent = (LinearLayout) findViewById(R.id.parent); 
LayoutInflater inflater = getLayoutInflater(); 
TableLayout t = (TableLayout) inflater.inflate(R.layout.category_list, parent);