首页 > 解决方案 > 如何调整文本对齐到文本视图的两个角

问题描述

目前我的布局如下所示:

在此处输入图像描述

布局代码:

 <TextView
            style="@style/style_textviewsProfile"
            android:id="@+id/textViewBusID"
            android:text="Bus ID:     " />

   <style name="style_textviewsProfile">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@color/Black</item>
        <item name="android:textSize">20dp</item>
        <item name="android:layout_marginTop">10dp</item>
    </style>

但我想将文本调整到文本视图的一个角和另一个角,例如将总线 ID调整到最左边,将 as-676调整到最右边。我需要对我的 XML 文件进行哪些更改?

标签: androidxmllayout

解决方案


您可以添加一个水平方向的相对布局,并在其中添加两个文本视图,然后配置它们的方向。例如;

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_height="wrap_content"
        android:text="Name:"
        android:layout_alignParentLeft="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_alignParentEnd="true"
        android:text="Tiwari Ji"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />

</RelativeLayout>

将一个 TextView 对齐到父级的开头,另一个对齐到父级的末尾应该会给你想要的结果。

您可以看到上面的代码在屏幕上呈现的内容: Properly Aligned text

使用 LinearLayout 也可以实现相同的壮举

 <LinearLayout
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_margin="16dp"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Name:" />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:gravity="right"
        android:text="Tiwari Ji"
        android:layout_height="wrap_content" />
</LinearLayout>

在这里,我对 LinearLayout 中的 TextView 赋予了相同的权重,通过赋予它们android:layout_weight="1"android:layout_width="0dp".

然后通过提供android:gravity="right"确保布局内的文本与视图最右边缘的末端对齐。

乐于助人,有什么问题可以问。


推荐阅读