Table Layout in JAVA in Android Studio
TableLayout Overview
TableLayout is a ViewGroup that arranges its children in rows and columns, providing a grid-like structure. Each row in the table is represented by a TableRow element within the TableLayout, and each cell (column) within a row is represented by a View, typically a TextView or another layout.
XML Attributes:
android:layout_width and android:layout_height: Specify the width and height of the TableLayout.
android:stretchColumns: Indicates which columns should stretch to fill any remaining space. It takes a comma-separated list of column indices (0-based).
android:shrinkColumns: Indicates which columns should shrink if the table is too wide. Similar to stretchColumns, it takes a comma-separated list of column indices.
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<!-- Rows and cells go here -->
</TableLayout>
TableRow
TableRow is used to group the views within a row in a TableLayout. It is a subclass of LinearLayout with a horizontal orientation.
XML Attributes:
android:layout_width and android:layout_height: Specify the width and height of the TableRow.
Other layout-related attributes like padding, margin, etc.
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Cells (TextViews, ImageViews, etc.) go here -->
</TableRow>
TableCell (TextView, etc.)
Individual cells within a TableRow are typically represented by View elements like TextView, ImageView, etc.
XML Attributes:
android:layout_width and android:layout_height: Specify the width and height of the cell.
android:padding: Sets padding for the cell.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Cell Content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Cell Content" />
Dynamically Adding Rows and Cells (Java)
To dynamically add rows and cells to a TableLayout in Java:
TableLayout tableLayout = findViewById(R.id.tableLayout);
TableRow newRow = new TableRow(this);
TextView cell1 = new TextView(this);
cell1.setText("Dynamic Row, Col 1");
cell1.setPadding(8, 8, 8, 8);
TextView cell2 = new TextView(this);
cell2.setText("Dynamic Row, Col 2");
cell2.setPadding(8, 8, 8, 8);
newRow.addView(cell1);
newRow.addView(cell2);
tableLayout.addView(newRow);
This Java code snippet demonstrates how to programmatically create a TableRow, add TextViews to it, and then add the TableRow to the TableLayout.
This overview provides a foundation for understanding and using TableLayout in Android. For more detailed information, examples, and advanced features, refer to the official Android documentation: TableLayout.
Comments
Post a Comment