8

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

hossam scott
  • 466
  • 5
  • 28
  • 2
    Take a look on autosizing TextView documentation: https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview – Domin Oct 28 '18 at 10:31
  • 2
    but thats one for API level 26 –  Oct 28 '18 at 10:35
  • So what's the problem? The question has already been answered. – aminography Nov 01 '18 at 10:12
  • I think There's no native support but, You can check out this answer https://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds – hossam scott Oct 28 '18 at 10:33

2 Answers2

18

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"
                    />
Reza.Abedini
  • 2,227
  • 2
  • 16
  • 18
  • 3
    as mentioned https://www.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.. – Muahmmad Tayyib Dec 10 '19 at 07:41
4

TextViewCompat from AndroidX is the official solution for your problem.

Fung
  • 961
  • 1
  • 8
  • 17
  • 4
    which works only for 26+ Android, but we can use `AppCompatTextView` and `app:autoSizeMaxTextSize="100sp" app:autoSizeMinTextSize="12sp" app:autoSizeTextType="uniform"` – user924 Feb 04 '20 at 12:00
  • 1
    Here's some documentation about the support libraries: https://developer.android.com/develop/ui/views/text-and-emoji/autosizing-textview#using-support-library_1 – James Aug 31 '22 at 05:40