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

背景

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

效果图


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

实现方案

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

  • 实现描述列居左对齐
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/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://schemas.android.com/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>
发布了407 篇原创文章 · 获赞 90 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/yinxing2008/article/details/104206418
今日推荐