Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling textSize in a TextView

Say I have a TextView of a particular size (doesn't really matter what... fill_parent, 20dip, whatever). Is it possible to tell the text to shrink/grow in size to fit the available space without doing a lot of math?

like image 378
Jeremy Logan Avatar asked Feb 19 '10 04:02

Jeremy Logan


People also ask

How do you get 3 dots at the end of a TextView text?

You are applying to your TextView a compound Drawable on the right.. to make the three dots appear in this scenario, you have to apply a android:drawablePadding="{something}dp" attribute to the TextView as well. Hope it helps!

How do I resize text on android?

To make your font size smaller or larger: On your device, open the Settings app. Search and select Font size. To change your preferred font size, move the slider left or right.

Should I use SP or DP android?

When setting text sizes, you should normally use sp , or “scale-independent pixels”. This is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference.


1 Answers

Well, it's a little simpler than "a lot of complex maths", but there's a hack solution I use for this that's workable if the width of your text isn't too far off from the width of your textview.

    // HACK to adjust text width
    final int INITIAL_TEXTSIZE = 15;
    final int TEXTVIEW_WIDTH = textviewBackground.getIntrinsicWidth(); // I use the background image to find the width, but you can use a fixed value or whatever other method you prefer.
    final String text = ...;
    textView.setText( text );

    int size = INITIAL_TEXTSIZE;
    while( textview.getPaint().measureText(text) > TEXTVIEW_WIDTH )
        textview.setTextSize( --size );

If the width of your text can be significantly different than the width of your TextView, it might be better to employ a binary search instead of a linear search to find the right font size.

Not saying this is an ideal solution, but it's an expedient one if you don't often need to adjust your textsize. If you need to frequently adjust your textsize, it might be better to do some complex maths.

like image 184
emmby Avatar answered Oct 27 '22 16:10

emmby