Setting number of columns programmatically in TableLayout

此生再无相见时 提交于 2019-12-06 00:51:23

问题


I have an XML layout which contains a TableLayout with an unknown number of TableRows... The number of Rows will be established durin runtime, what I do know though is that I want two columns... So I have a couple of questions regarding this :

    - is there a way to set the whole TableLayout to have 2 columns ?

- is there a way programmatically to give an id to the (during runtime) created TableRows which will be placed within the TableLayout, so I can reference them later on from other parts of the software ?

回答1:


You can build your table rows via XML parts and LayoutInflater. Say you had this as your table_cell.xml:

<TextView android:id="@+id/text"
    android:text="woot" />

And this as your table_row.xml (unless you're doing something fancy with your TableRow, you may not need to put it in it's own XML file, and instead just create it programmatically. The result will be the same):

<TableRow />

Assuming your TableLayout reference was called "table", you could do something like this:

TableLayout table = (TableLayout)findViewById(R.id.table);
LayoutInflater inflater = getLayoutInflater();

for(int i = 0; i < 5; i++) {
    TableRow row = (TableRow)inflater.inflate(R.layout.table_row, table, false);
    View v = (View)inflater.inflate(R.layout.table_cell, row, false);
    row.addView(v);
    v = (View)inflater.inflate(R.layout.table_cell, row, false);
    row.addView(v);

    // you can store your reference to `row` here for later use
    table.addView(row);
}

With this technique, you can still set up your layout in XML, making it easier to read/organize/edit, and you still have programmatic control over how many columns and rows are in the table. You can also store references to each table row for later use.



来源:https://stackoverflow.com/questions/2729992/setting-number-of-columns-programmatically-in-tablelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!