I want a TextView which adjusts the font size so that the text in the view will automatically expand (or shrink) to fill the full width of the view. I thought I might be able to do this by creating a customised TextView which overrides onDraw() as follows:
public class MaximisedTextView extends TextView {
// (calls to super constructors here...)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
TextPaint textPaint = this.getPaint();
Rect bounds = new Rect();
String text = (String)this.getText(); // current text in view
float textSize = this.getTextSize(); // current font size
int viewWidth = this.getWidth() - this.getPaddingLeft() - this.getPaddingRight();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int textWidth = bounds.width();
// reset font size to make text fill full width of this view
this.setTextSize(textSize * viewWidth/textWidth);
}
}
However, this sends the app into an endless loop (with the text size growing and shrinking slightly each time!), so I’m clearly going about it the wrong way. Does the call to setTextSize() trigger an invalidate so that onDraw is called again, endlessly?
Is there a way I can prevent the recursive call (if that’s what is happening)? Or should I be going about it a completely different way?
Yes, that’s probably what is hapening. If you take a look of the source code of
setTextSizeyou will see that it will call this method:So, if you are doing the hard work of overriding the
onDrawmethod, why don’t you use directly some of thedrawTextmethods of theCanvasclass?