In-depth explanation of TableLayout (table layout) in Android basics.

TableLayout is a layout container in Android used for creating table layouts, allowing for the creation of tables with rows and columns in the interface. One of the key features of TableLayout is that each row can contain multiple columns, with column widths adjusting automatically based on the content.

TableLayout的使用步骤如下:

  1. Add a TableLayout widget in the layout file.
<TableLayout
    android:id="@+id/tableLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</TableLayout>
  1. Get the instance of the TableLayout control in the Activity.
TableLayout tableLayout = findViewById(R.id.tableLayout);
  1. Create a TableRow object and add it to the TableLayout.
TableRow row = new TableRow(this);
tableLayout.addView(row);
  1. Create a TextView or another View object and add it to a TableRow.
TextView textView = new TextView(this);
textView.setText("Text");
row.addView(textView);
  1. Repeat steps 3 and 4 to create and add multiple TableRow and View objects.

Apart from dynamically creating table layouts using code, you can also statically create table layouts in the layout file. When adding TableRows and Views, it is important to consider the following points:

  1. In each row, the width of each column will adjust automatically based on the content, and you can control the ratio of column widths by setting the android:layout_columnWeight attribute.
  2. Multiple columns can be merged by setting the android:layout_span attribute.
  3. You can control the position of a View within a cell by setting the android:layout_gravity attribute (such as centering or aligning to the left).

TableLayout also provides some common methods such as getting the number of TableRows, getting a specific TableRow at a certain position, and getting a specific View at a certain position, which can be used to dynamically manipulate the table layout.

In summary, TableLayout is a layout container used for creating table layouts, allowing for the creation of a table structure with rows and columns in the interface. It can be flexibly created and manipulated through code or layout files.

bannerAds