2011-11-26 85 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);