Android TextView with Auto Sized Content

While working on an Android project lately I was looking for a solution to auto-size text in a TextView similar to the way the iPhone ADK allows you to select “fit text to box”. I couldn’t find any reference to something similar in the Android SDK so I had to roll my own TextView subclass.

Now all I have to do is call setFitTextToBox(true) on the TextFitTextView after allocation. Enjoy!

public class TextFitTextView extends TextView {

	static final String TAG = "TextFitTextView";
	boolean fit = false;
	
	public TextFitTextView(Context context) {
		super(context);
	}

	public TextFitTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public TextFitTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setFitTextToBox( Boolean fit ) {
		this.fit = fit;
	}
	
	protected void onDraw (Canvas canvas) {
		super.onDraw(canvas);
		if (fit) _shrinkToFit();
	}
	
	protected void _shrinkToFit() {
		
		int height = this.getHeight();
		int lines = this.getLineCount();
		Rect r = new Rect();
		int y1 = this.getLineBounds(0, r);
		int y2 = this.getLineBounds(lines-1, r);
		
		float size = this.getTextSize();
		if (y2 > height && size >= 8.0f) {
			this.setTextSize(size - 2.0f);
			_shrinkToFit();
		}
		
	}
}