Text/Layout Alignment in Android (textAlignment, gravity)
What's the difference between android:textAlignment
and android:gravity
?
Solution 1:
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.
Solution 2:
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+:
Solution 3:
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
.
Solution 4:
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.