新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

Android之TableLayout表格布局如何用

发布时间:2023-08-02 09:29:16

Android之TableLayout表格布局如何用

在Android中,TableLayout是一种用于创建表格布局的布局容器。可使用TableLayout来创建包括多行多列的表格,并在每一个单元格中放置其他视图或控件。
以下是使用TableLayout的基本步骤:
1. 在XML布局文件中添加TableLayout标签:
```xml
android:id="@+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">

```
2. 在Activity中获得TableLayout实例:
```java
TableLayout tableLayout = findViewById(R.id.tableLayout);
```
3. 创建TableRow并将其添加到TableLayout中:
```java
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT
);
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(rowParams);
tableLayout.addView(tableRow);
```
4. 在TableRow中添加单元格(TableCell)并设置内容:
```java
TextView textView = new TextView(this);
textView.setText("Cell 1");
tableRow.addView(textView);
TextView textView2 = new TextView(this);
textView2.setText("Cell 2");
tableRow.addView(textView2);
```
5. 可以重复步骤4以创建更多的单元格,并将它们添加到同一行的TableRow中。
6. 可以重复步骤3和步骤4以创建更多的行,并将它们添加到TableLayout中。
```java
TableRow tableRow2 = new TableRow(this);
tableRow2.setLayoutParams(rowParams);
tableLayout.addView(tableRow2);
// 添加单元格到第二行
...
```
通太重复步骤4和步骤5,可以创建任意数量的行和单元格,并在TableLayout中进行布局。