views:

391

answers:

2

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?

+1  A: 

Not that I am aware of, sorry.

CommonsWare
+2  A: 

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.

Mike