将表格数据显示在TableLayout中
时间: 2024-03-16 21:43:47 浏览: 13
要在TableLayout中显示表格数据,需要先创建TableRow视图,并将每个单元格添加为TableRow的子视图。然后将每个TableRow添加为TableLayout的子视图。以下是一个简单的示例代码:
```java
TableLayout tableLayout = findViewById(R.id.tableLayout);
// 创建表头
TableRow headerRow = new TableRow(this);
TextView header1 = new TextView(this);
header1.setText("Header 1");
TextView header2 = new TextView(this);
header2.setText("Header 2");
headerRow.addView(header1);
headerRow.addView(header2);
tableLayout.addView(headerRow);
// 添加数据行
for (int i = 0; i < data.length; i++) {
TableRow dataRow = new TableRow(this);
TextView data1 = new TextView(this);
data1.setText(data[i][0]);
TextView data2 = new TextView(this);
data2.setText(data[i][1]);
dataRow.addView(data1);
dataRow.addView(data2);
tableLayout.addView(dataRow);
}
```
在这个示例中,我们首先创建了一个TableLayout,然后创建了一个包含两个表头列的TableRow,并将其添加到TableLayout中。接下来,我们使用一个循环来遍历数据数组,并为每个数据行创建一个TableRow,并将每个单元格添加为其子视图。最后,将每个数据行添加到TableLayout中,以便在界面上显示表格数据。