What's the difference between android:textAlignment
and android:gravity
?
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.
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+:
android:textAlignment
is only available for API 17+, that is why there is no effect on lower versions. –
Portentous 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
.
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.
© 2022 - 2024 — McMap. All rights reserved.
textAlignment
so for instance you need to settextAlignment
as opposed togravity
when overridingSnackbar
default set up. ie.val textView = sb.view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text) textView.textAlignment = View.TEXT_ALIGNMENT_CENTER
– Ravid