I have been struggling more than I would have expected on this, here is my issue.
As you can see on the image below, I want my TextView
to be center
horizontally
in the parent
, but also align
vertical
center
with the view on the left.
The problem comes from the TextView
, the text can be longer, I want it to be on 2 lines with the attribute maxLength = 12
.
My XML:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="parent"
app:layout_constraintEnd_toStartOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/roundTextView"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/oval"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/descriptionTextView"
app:layout_constraintHorizontal_bias="0.3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/descriptionTextView"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:maxLength="12"
android:maxLines="2"
android:text="Long Text 2 Lines"
android:textAlignment="center"
android:textColor="@android:color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="@+id/roundTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/roundTextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
If I change the text, with something longer (more than 10 length), here is the result, it's fine.
But if I change to a small text, the result is not as expected because of the 0dp
height
. And if I put wrap_content
, the 2 lines text isn't working.
What is the right way of handling this situation?
By adding:
android:gravity="center_vertical"
android:maxLines="2"
the text always is shown vertically in the middle and there is no need to android:textAlignment="center"
.