温馨提示×

Android之TableLayout表格布局怎么用

小亿
100
2023-07-31 20:12:12
栏目: 编程语言

在Android中,TableLayout是一种用于创建表格布局的布局容器。可以使用TableLayout来创建包含多行多列的表格,并在每个单元格中放置其他视图或控件。

以下是使用TableLayout的基本步骤:

  1. 在XML布局文件中添加TableLayout标签:
<TableLayout
android:id="@+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TableLayout>
  1. 在Activity中获取TableLayout实例:
TableLayout tableLayout = findViewById(R.id.tableLayout);
  1. 创建TableRow并将其添加到TableLayout中:
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);
  1. 在TableRow中添加单元格(TableCell)并设置内容:
TextView textView = new TextView(this);
textView.setText("Cell 1");
tableRow.addView(textView);
TextView textView2 = new TextView(this);
textView2.setText("Cell 2");
tableRow.addView(textView2);
  1. 可以重复步骤4以创建更多的单元格,并将它们添加到同一行的TableRow中。

  2. 可以重复步骤3和步骤4以创建更多的行,并将它们添加到TableLayout中。

TableRow tableRow2 = new TableRow(this);
tableRow2.setLayoutParams(rowParams);
tableLayout.addView(tableRow2);
// 添加单元格到第二行
...

通过重复步骤4和步骤5,可以创建任意数量的行和单元格,并在TableLayout中进行布局。

0