一、基本概念
AndroidTableLayout是一個可以用於布局的視圖容器,和HTML中的table類似,可以將視圖按照行列的形式組織在一起,方便用戶查看和使用。
TableLayout是一個容器,以行為單位,每一行可以包含任意數目的單元格(TableCells),單元格可以包含任意類型的視圖組件,包括TextView、ImageButton等。
TableLayout可以幫助我們快速構建布局,在適當的場景下也可以提高布局的性能。
二、使用方法
首先需要在布局文件中聲明TableLayout:
<TableLayout android:id="@+id/myTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content"> </TableLayout>
然後根據需要添加TableRow,每個TableRow代表一行,可以在TableRow中添加TableCells:
TableLayout tableLayout = (TableLayout) findViewById(R.id.myTableLayout); TableRow tableRow = new TableRow(this); tableLayout.addView(tableRow);
TableCells可以添加任意類型的視圖組件,一般使用TextView或ImageButton:
TextView textView = new TextView(this); textView.setText("Hello, World!"); tableRow.addView(textView);
如果需要給TableLayout添加外邊距或內邊距,可以使用android:padding和android:layout_margin屬性。
三、常用屬性
下面是常用的一些屬性:
1. android:shrinkColumns:用於指定縮短列的優先級,多個列之間使用逗號隔開。
<TableLayout android:id="@+id/myTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:shrinkColumns="1,2"> </TableLayout>
2. android:stretchColumns:用於指定拉伸列的優先級,多個列之間使用逗號隔開。
<TableLayout android:id="@+id/myTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="1,2"> </TableLayout>
3. android:collapseColumns:用於指定需要隱藏的列,多個列之間使用逗號隔開。
<TableLayout android:id="@+id/myTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:collapseColumns="2,3"> </TableLayout>
4. android:layout_span:用於指定單元格的跨行或跨列數量。
<TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Spanned Cell" android:layout_span="2"/> </TableRow>
四、樣例代碼
下面是一個簡單的例子,展示了如何使用TableLayout布局一個簡單的圖書列表:
<TableLayout android:id="@+id/bookTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:stretchColumns="0,1,2"> <TableRow> <TextView android:text="書名" android:textStyle="bold"/> <TextView android:text="作者" android:textStyle="bold"/> <TextView android:text="出版社" android:textStyle="bold"/> </TableRow> <TableRow> <TextView android:text="《Android編程權威指南》"/> <TextView android:text="Bill Phillips,Chris Stewart"/> <TextView android:text="人民郵電出版社"/> </TableRow> <TableRow> <TextView android:text="《Head First Android開發》"/> <TextView android:text="Dawn Griffiths, David Griffiths"/> <TextView android:text="中國電力出版社"/> </TableRow> </TableLayout>
五、總結
AndroidTableLayout是Android中常用的一個布局容器,可以將視圖按照行列的形式組織在一起,方便用戶查看和使用。在適當的場景下,使用TableLayout可以提高布局的性能。
原創文章,作者:DEGH,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/134019.html