Android中的文本/布局对齐(textAlignment,gravity)

问题描述 投票:49回答:4

android:textAlignmentandroid:gravity有什么区别?

android mobile layout text-alignment layout-gravity
4个回答
47
投票

我只能看到textAlignment是View Class的成员,而gravity是TextView类的成员。因此,对于TextView及其子类,您可以使用重力,同时可以对所有视图使用textAlignment。

由于TextView及其子类需要更多的文本对齐功能,因此您可以看到有更多的重力选项,其中textAlignment只有基本选项。虽然这只是我的猜测,因为我没有找到任何有关差异的明确文件。

您可以看到这两个文档链接:textAlignmentgravity


10
投票

使用API​​ 15,android:textAlignment可能没有所需的结果。下面的片段尝试使用TextView居中第一个android:textAlignment="center"对象。第二个使用android:gravity="center_horizontal"textAlignment没有效果,而重力工作正常。使用API​​ 17+,textAlignment按预期将文本居中。

为了确保您的文本与所有版本正确对齐,我会选择重力。

<LinearLayout
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Fri"
        android:textAlignment="center"
        android:textSize="16sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="29"
        android:gravity="center_horizontal"
        android:textSize="18sp" />

</LinearLayout>

API 15中的结果布局:

API 17+中的最终布局:


5
投票

据我所见,textAlignment似乎大多未使用过。根据它的描述,它应该做正确或左对齐。重力似乎是一个改进的textAlignment。


2
投票

另一点没有明确提到:

如果您的应用程序已禁用RTL支持,例如android:supportsRtl="false"在清单application标签,然后View textAlignment不适用于文本定位,而TextView gravity工作。

更喜欢gravity的另一个原因。

© www.soinside.com 2019 - 2024. All rights reserved.