AndroidTableLayout详解

发布时间:2023-05-21

一、基本概念

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可以提高布局的性能。