Auto adjust text size to fit the layout Android

10,295

Solution 1

Android officialy supports autosizing.for implementing dynamic size you should set autoSizeTextType attribute to uniform and set autoSizeMaxTextSize and autoSizeMinTextSize attributes to your desired size.

*attention : for apis below 26 you should use 'app' prefix for attributes instead of 'android' .

and finally you should have a textView like this for stretching text to screen-width:

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:maxLines="1"
                    android:text="Hello, how are you today"
                    android:textSize="100sp"
                    app:autoSizeMaxTextSize="100sp"
                    app:autoSizeMinTextSize="12sp"
                    app:autoSizeStepGranularity="2sp"
                    app:autoSizeTextType="uniform"
                    />

Solution 2

TextViewCompat from AndroidX is the official solution for your problem.

Share:
10,295
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    Is there's way to change the text size to fit screen-width ? i have Header with long title, the problem is on small size screen that title goes to another line. i would like to change font size to fit the whole text in 1 line

  • Muahmmad Tayyib
    Muahmmad Tayyib over 4 years
    as mentioned youtube.com/watch?v=JYrpEAz_A1U avoid using layout height to wrap content, instead use match_parent or specified height... otherwise this could cause unexpected results..
  • user924
    user924 over 4 years
    which works only for 26+ Android, but we can use AppCompatTextView and app:autoSizeMaxTextSize="100sp" app:autoSizeMinTextSize="12sp" app:autoSizeTextType="uniform"