如何使用可编程方式从XML创建TableLayout?

Fer*_*and 2 layout android

我试图使用可编程方式从资源(xml)将TableLayout添加到LinearLayout.

添加的TableLayout计数是动态的.它将介于1到10之间.我认为从资源xml中创建它是更好的方法.因为设计不会破裂.

怎么做?

实际上我不知道如何从XML创建新实例.

请帮忙.家伙.

提前致谢.

syn*_*nic 5

像这样的东西:

TableLayout table = (TableLayout)findViewById(R.id.table);

LayoutInflater inflater = getLayoutInflater();

for(int i = 0; i < 10; i++) {
    TableRow row = (TableRow)inflater.inflate(R.id.table_row, 
        table, false);

    TextView text = (TextView)row.findViewById(R.id.text);
    text.setText("row: " + i);
    // other customizations to the row

    table.addView(row);
}
Run Code Online (Sandbox Code Playgroud)

table_row.xml看起来像这样:

<TableRow xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:id="@+id/text" />
    <TextView android:id="@+id/text2" />
</TableRow>
Run Code Online (Sandbox Code Playgroud)

这样,您仍然可以在XML中创建表行,并且行数是动态的.