androidandroid-layouttextviewandroid-constraintlayoutandroid-textview-autosize

How can I get two auto-sized textviews to be centered vertically in the middle?


enter image description here enter image description here

I want the look on the left side. With fixed text size I have no problem creating that layout but I want to have auto-sized text sizes. Currently my best attempt at it produces the layout on the right side.

The code for my failed attempt is:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout1"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@drawable/border"
    android:gravity="center"
    android:orientation="vertical">


    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/TextView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        app:layout_constraintTop_toTopOf="parent"
        android:text="Top"

        app:layout_constraintBottom_toTopOf="@+id/TextView2"
        app:layout_constraintVertical_bias="0"
        app:autoSizeMaxTextSize="40dp"
        app:autoSizeMinTextSize="4dp"
        app:autoSizeTextType="uniform" />
    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/TextView2"
        app:layout_constraintTop_toBottomOf="@+id/TextView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"

        app:layout_constraintBottom_toBottomOf="parent"
        android:text="Bottom"
        app:autoSizeMaxTextSize="24dp"
        app:autoSizeMinTextSize="4dp"
        app:autoSizeTextType="uniform"/>
</android.support.constraint.ConstraintLayout>

It produces


Solution

  • Easiest way would be to change the gravity of both TextViews so the first one is at the bottom center of its area and the second one is at the top center. To achieve it you should set android:gravity="bottom|center_horizontal" on the first TextView and android:gravity="top|center_horizontal" on the second.

    Result:

    enter image description here

    As a side note it is not advised to use match_parent for children of the ConstraintLayout as metioned in the documentation:

    Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".