2011-11-26 74 views
0

我想將行添加到我在XML文件中定義的TableLayout中。 XML文件包含表格的標題行。以XML格式定義佈局時以編程方式創建表格行

我可以很好地使用各種教程中的信息添加新行,但爲新行設置佈局所需的代碼是一個可怕的混亂,它似乎是一個痛苦的屁股來維護每當頭的佈局行更改。

是否有可能創建新的行到TableLayout,同時仍然定義在XML中的行佈局?例如,在XML中定義一個模板行,獲取代碼中的句柄,然後在需要時克隆模板。

或者是正確的方式做到這一點完全不同?

回答

4

您提出的方法可以正常工作,它或多或少地匹配填充ListView項目時使用的常用模式。

定義包含單個行的佈局。使用LayoutInflater.from(myActivity)獲取LayoutInflater。使用這個充氣器可以使用您的佈局創建新的行,如模板。一般來說,您會希望使用LayoutInflater#inflate的三參數形式,通過false獲取第三個attachToRoot參數。

假設您想在每個項目中使用帶有標籤和按鈕的模板佈局。它看起來是這樣的:(雖然你將定義你的錶行代替)

RES /佈局/ item.xml:

<LinearLayout android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 
    <TextView android:id="@+id/my_label" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 
    <Button android:id="@+id/my_button" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 
</LinearLayout> 

然後點在哪裏,你誇大:

// Inflate the layout and find the component views to configure 
final View item = inflater.inflate(R.layout.item, parentView, false); 
final TextView label = (TextView) item.findViewById(R.id.my_label); 
final Button button = (Button) item.findViewById(R.id.my_button); 

// Configure component views 
label.setText(labelText); 
button.setText(buttonText); 
button.setOnClickListener(buttonClickListener); 

// Add to parent 
parentView.addView(item); 
相關問題