How to auto-sizing text size in Android

· 1 min read

Most of the time we can display the text as follows:

<TextView
    android:id="@+id/text_question_no"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:text="some text"
    android:fontFamily="@font/museo700regular"
    android:textColor="@color/colorSlangBlack"
    android:gravity="center_vertical|left"
    android:textSize="22sp" />

The TextView will also be autosized according to the text content length. However, sometimes we want the TextView to be a fixed area and the text size can be resized depending on the size of the screen.

An example of this is shown in 4 sections on the home screen:

Text is a bit messy on right screen

As you can see, the text on the Pixel and Huawei Mate 9 is showing a bit differently. This might be even worse on some of the other screens too. Is there any way we can auto-adjust the text on different screens? The answer is yes, and there are two ways of doing this. We can either use:

  • TextViewCompat: Official component from Android, but the minSDK should ≥ 26.
  • AppCompatTextView compatible for all the sdks. See the following code for more details.

Example layouts:

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/text_question_no"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:text="some text"
    android:fontFamily="@font/museo700regular"
    android:textColor="@color/colorSlangBlack"
    android:gravity="center_vertical|left"
		app:autoSizeMaxTextSize="22sp"
    app:autoSizeMinTextSize="18sp"
    app:autoSizeTextType="uniform"
/>

After the change, the layout:

Wala~ If you like this story, please 👏👏👏, I will continue to share more tutorials.