You can use either layout_gravity
or gravity
for text centring. With layout_gravity
:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:breakStrategy="balanced"
/>
Short stretches of text will be displayed as:
[ Hello ]
While long stretches will be: (A)
[ One lemming looking ]
[ up. ]
So you might add:
android:gravity="center"
And you'll get: (B)
[ One lemming looking ]
[ up. ]
However, I want to achieve this: (C)
[ One lemming looking ]
[ up. ]
A does not look good, because text does not appear centred. This is especially true if there are more centred elements in the layout.
B does not look good, because the very short word "up" was put into the centre. Even if the text is longer, it doesn't look good, because the text has two jagged edges (left + right) instead of just one (to the right).
C is the same as A, but correctly centred. The reason why A does not look centred is because wrap_content
assumes the width of the TextView is as wide as the parent's when the text wraps on another line, and does not compute the actual width of the block of text.
So, how do I achieve C? Is it possible?
Here's the full layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<TextView
android:id="@+id/primary_form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="start"
android:textAppearance="@style/TextAppearance.AppCompat.Headline"
android:textColor="@color/text_primary_on_lt"
android:breakStrategy="balanced"
tools:text="Primary form adfahdkahdfa "
/>
<TextView
android:id="@+id/secondary_form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@color/text_secondary_on_lt"
android:textStyle="italic"
android:typeface="serif"
android:breakStrategy="balanced"
tools:text="Secondary form"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>