首页 > 解决方案 > How to Shrink Font in Order to fit Inside Width of View in Android?

问题描述

Let's say we have a single-line text view with a fixed width. We want to display a string in it, but we don't know how long the string is yet.

We want the string to shrink as necessary in order to fit inside the text view without truncating.

In IOS, this accomplished with this:

BEFORE:

enter image description here

enter image description here

enter image description here

AFTER:

enter image description here

enter image description here

What is the Android equivalent?

I have consulted this and tried to test it out in code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tvc);
        tv.setText("aa aaa a aaaaaaa aaaadfgd gsfg fsdg dfs gdfs gds fg dsg dsg sdfg dsf g zzzzzzzzzz");

        TextViewCompat.setAutoSizeTextTypeWithDefaults(tv, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);


    }

but was dismayed to find that it is not shrinking the font automatically to fit width, but rather expanding the font to fit height... with the string being truncated even more.

Please note: this question is different than (Auto Scale TextView Text to Fit within Bounds) because it doesn't have the same requirements: I am talking strictly about a single-line textview with a width restriction... and none of the answers in that question are satisfactory.

标签: androidviewandroid-edittexttextviewfont-size

解决方案


I suggest AutofitTextView. In Android, autofit TextView is not native supported so you have to customize.


推荐阅读