2011-03-08 28 views
14

我想用多列的Android創建一個表。我看到的大多數例子都是2列。 (我是新來的Java和Android)。我需要3-4列,我應該能夠在表中動態添加行。任何人都可以提供我一個示例代碼。 (我使用的Eclipse中取勝7)如何在Android中使用多列創建表格?

回答

23

我假設你在談論數據庫中的一個TableLayout視圖,而不是表?

如果是的話,這裏有一個表有三列三行的XML實例。

每個<的TableRow>元素在表中創建一個行,並且在元件內部的每個視圖創建一個「列」。我用TextViews,但他們可以ImageViews,EditText上,等

<?xml version="1.0" encoding="utf-8"?> 

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id = "@+id/RHE" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0" 
     android:padding="5dp"> 

    <TableRow android:layout_height="wrap_content"> 
     <TextView 
      android:id="@+id/runLabel" 
      android:text="R" 
      android:layout_height="wrap_content" 
      /> 
     <TextView 
      android:id="@+id/hitLabel" 
      android:text="H" 
      android:layout_height="wrap_content" 
      /> 
     <TextView 
      android:id="@+id/errorLabel" 
      android:text="E" 
      android:layout_height="wrap_content" 
      /> 
    </TableRow> 

    <TableRow android:layout_height="wrap_content"> 
     <TextView 
      android:id="@+id/visitorRuns" 
      android:text="0" 
      android:layout_height="wrap_content" 
      /> 
     <TextView 
      android:id="@+id/visitorHits" 
      android:text="0" 
      android:layout_height="wrap_content" 
      /> 
     <TextView 
      android:id="@+id/visitorErrors" 
      android:text="0" 
      android:layout_height="wrap_content" 
      /> 
    </TableRow> 

    <TableRow android:layout_height="wrap_content"> 
     <TextView 
      android:id="@+id/homeRuns" 
      android:text="0" 
      android:layout_height="wrap_content" 
      /> 
     <TextView 
      android:id="@+id/homeHits" 
      android:text="0" 
      android:layout_height="wrap_content" 
      /> 
     <TextView 
      android:id="@+id/homeErrors" 
      android:text="0" 
      android:layout_height="wrap_content" 
      /> 
    </TableRow> 
</TableLayout> 

在代碼中動態地改變這些,你有這樣的事情:

// reference the table layout 
TableLayout tbl = (TableLayout)findViewById(R.id.RHE); 
// delcare a new row 
TableRow newRow = new TableRow(this); 
// add views to the row 
newRow.addView(new TextView(this)); // you would actually want to set properties on this before adding it 
// add the row to the table layout 
tbl.addView(newRow); 
+0

是的,我想表格佈局視圖。列未正確定位。如何定位列?我如何動態添加行? – narayanpatra 2011-03-08 06:10:01

+0

我不確定你的意思是「沒有正確定位」。 TableLayout將根據其屬性進行調整,就像內部的項目一樣。也許如果你發佈了你的xml以及你希望看到的內容,我們就有更多的能力來回答這個問題。 – Peter 2011-03-08 06:18:39

+0

我原樣使用了xml文件的代碼。只需更改前兩行。即<?xml version =「1.0」encoding =「utf-8」?> narayanpatra 2011-03-08 06:29:45

相關問題