How to make Autosizing TextViews in Android

Full project with source code to make the autosizing feature which was introduced with Android Oreo (API level 26). By setting autoSizeTextType to “uniform” the text can now grow and shrink in it’s size depending on it’s room in the TextView. We will also learn how to change the minTextSize, maxTextSize, granularity and how to define an array of different size steps

Table of Contents

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="tech.codingpoint.autosizingtextviewexample.MainActivity">

    <TextView
        android:layout_width="50sp"
        android:layout_height="50sp"
        android:text="Hello World!"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="20sp"
        app:autoSizePresetSizes="@array/autosize_text_sizes"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingPrefix" />

</android.support.constraint.ConstraintLayout>

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <array name="autosize_text_sizes">
        <item>10sp</item>
        <item>50sp</item>
        <item>150sp</item>
    </array>

</resources>

Leave a Comment