背景

有时以列表形式展示控件时,需要保持上下控件对齐.

效果图

安卓利用TableLayout实现控件列对齐_android

“用户账号:”和“密码:”居左或居右对齐,同时后面的输入框也对齐.

实现方案

利用TableLayout实现,里面嵌套TableRow.

  • 实现描述列居左对齐
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http:///apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户账号:" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="100dp" />
</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码:" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="100dp" />
</TableRow>
</TableLayout>

  • 实现描述列居右对齐
    在TextView中增加了​​android:textAlignment="textEnd"​​属性
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http:///apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户账号:"
android:textAlignment="textEnd" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="100dp" />
</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码:"
android:textAlignment="textEnd" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="100dp" />
</TableRow>
</TableLayout>