Auto adjust text size to fit the layout Android

Viewed 12304

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

2 Answers

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"
                    />

TextViewCompat from AndroidX is the official solution for your problem.

Related