2012-01-06 51 views
1

如果我計劃單獨動態更新單元格,應該如何實現15乘15格的表格?包含在表格中的XML佈局中的ID

我開始在main.xml中創建表格,但我不想用一個代碼體中的15個TableRow元素和15個元素來描述表格。我覺得即使把桌子本身放在單獨的文件中也太笨重。可以創建一個包含該行的表的行和文件的文件15次,併爲每個單元格動態分配不同的ID?

回答

1

你可以做comething像:

public void generateTable() { 
    TableLayout tv = new TableLayout(context); 

    for (int y = 0; y < 15; y++) { 
     TableRow tr = new TableRow(context); 
     for (int x = 0; x < 15; x++) { 
      TextView tv = new TextView(context); 
      tr.addView(tv); 
      tv.setText("ID: " + (y*15 + x)); 
      tv.setId(y*15 + x); 
      // And to allow for easy reading 
      if (y*15+x % 2 == 0) 
       tv.setBackgroundColor(0xffff0000); 
      else 
       tv.setBackgroundColor(0xff0000ff); 
     } 
    } 
} 
+0

哪些時要使用的佈局,當以編程方式構建它的普遍接受的準則? – 2012-01-07 05:07:51

+0

真的沒有。試着讓它乾淨。 – AedonEtLIRA 2012-01-09 03:20:45

0

從XML

TableLayout tl = (TableLayout) findViewById(R.id.content_table); 

也可以用XML創建一個錶行作爲tablerow.xml.This將幫助您創建一個表的佈局像這樣以更簡單的方式定義表格行佈局。我只添加1個TextView。

<TableRow xmlns:android="http://schemas.android.com/apk/res/android"> 
<TextView android:id="@+id/content" 
    android:singleLine="false" 
    /> 

LayoutInflater inflater = getLayoutInflater(); 

    for (int rowID = 0; rowID < 15; rowID++) { 
     TableRow row = (TableRow)inflater.inflate(R.id.tablerow, tl, false); 
     TextView content = (TextView)row.findViewById(R.id.content); 
     content.setId(rowID); 
     content.setText("this is the content"); 
     tl.addView(row); 
    }