Text/Layout Alignment in Android (textAlignment, gravity)

旧时模样 提交于 2019-11-28 20:02:42
stinepike

All I can see is that the textAlignment is a member of the View Class and the gravity is the member of TextView class. So for the TextView and its subclasses you can use the gravity while you can use the textAlignment for all Views.

As the TextView and its subclasses need some more text-aligning features, so you can see there are more options in gravity where in textAlignment there are only basic options. Although it is only my guess because I have not found any clear documentation about the difference.

You can see these two links of documentation: textAlignment and gravity.

Will P

With API 15, android:textAlignment may not have the desired result. The snippet below attempts to centre the first TextView object using android:textAlignment="center". The second uses android:gravity="center_horizontal". The textAlignment has no effect whereas the gravity works fine. With API 17+, textAlignment centres the text as expected.

To be certain that your text is aligned correctly with all releases, I'd go with gravity.

<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>

Resulting layout in API 15:

Resulting layout in API 17+:

As far as I've seen textAlignment seems to be mostly unused. By it's description, it should do just right or left alignment. Gravity seems to be an improved textAlignment.

Another point not explicitly mentioned:

If your application has RTL support disabled with e.g. android:supportsRtl="false" in manifest application tag, then View textAlignment does not work for text positioning while TextView gravity works.

Yet another reason to prefer gravity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!