在TableLayout设置列数编程 [英] Setting number of columns programmatically in TableLayout

查看:132
本文介绍了在TableLayout设置列数编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含有数目不详的TableRows的TableLayout一个XML布局... 行数将建立durin运行时,我知道的是,虽然我想两列... 所以,我有几个关于这个问题:

    - 有没有一种方法来设置整个TableLayout有2列

- 是有没有办法编程方式给一个id的(在运行时)创建TableRows将被放置在TableLayout中,这样我就可以从软件的其他部分引用它们以后?

解决方案

您可以通过XML部件和LayoutInflater建立自己的表行。说你有这个作为你的table_cell.xml:

 < TextView的机器人:ID =@ + ID /文
    机器人:文本=活泉/>
 

这是你的table_row.xml(除非你正在做一些花哨的与你的TableRow,你可能并不需要把它放在它自己的XML文件,而不是仅仅以编程方式创建它的结果会是一样的。):

 <的TableRow />
 

假设你TableLayout参考被称为表,你可以做这样的事情:

  TableLayout表=(TableLayout)findViewById(R.id.table);
LayoutInflater充气= getLayoutInflater();

的for(int i = 0;我小于5;我++){
    的TableRow行=(的TableRow)inflater.inflate(R.layout.table_row,桌子,假);
    视图V =(查看)inflater.inflate(R.layout.table_cell,行,假);
    row.addView(五);
    V =(查看)inflater.inflate(R.layout.table_cell,行,假);
    row.addView(五);

    //你可以在这里保存你的参考`row`供以后使用
    table.addView(行);
}
 

通过这种技术,你仍然可以建立在XML布局,使其更容易阅读/整理/编辑,你仍然有计划的控制多列和行如何在表中。也可以参考存储到每个表行,供以后使用。

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 ?

解决方案

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.

这篇关于在TableLayout设置列数编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆