《Android布局之TableLayout(表格布局)》
一、 说明
本文主要讲述Android开发的布局方式之一TableLayout (相对布局)
二、 所需工具
安卓开发工具(Android Studio)
三、 具体内容
准备工作:打开Android Studio新建一个空白样式的项目,并创建一个layout Resource File
第一步:把布局改为网格布局,
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableLayout>
第二步:添加组件,如Button等等,若只添加一个组件则会默认该组件占满一行,代码如下
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="组件一"
android:textSize="30dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="组件二"
android:textSize="30dp" />
</TableLayout>
效果图:
若要在同一行中添加多个组件则需要将组件添加到TableRow容器中,代码如下:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="组件一"
android:textSize="30dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="组件二"
android:textSize="30dp" />
</TableRow>
</TableLayout>
效果图:
若要设置组件所占区域的大小可以通过权重(layout_weight)来控制,代码如下:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="组件一"
android:textSize="30dp"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="组件二"
android:textSize="30dp"
android:layout_weight="1"/>
</TableRow>
</TableLayout>
效果图: