http://jeffreysambells.com/posts/2010/04/04/android-textview-with-auto-sized-content/
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();
}
}
}
<!-- TextView wrapped in the custom LinearLayout that expects one child TextView -->
<!-- This view should specify the size you would want the text view to be displayed at -->
<com.custom.ResizeView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="@+id/CustomTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
</com.custom.ResizeView>
public class ResizeView extends LinearLayout {
public ResizeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ResizeView(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// oldWidth used as a fixed width when measuring the size of the text
// view at different font sizes
final int oldWidth = getMeasuredWidth() - getPaddingBottom() - getPaddingTop();
final int oldHeight = getMeasuredHeight() - getPaddingLeft() - getPaddingRight();
// Assume we only have one child and it is the text view to scale
TextView textView = (TextView) getChildAt(0);
// This is the maximum font size... we iterate down from this
// I've specified the sizes in pixels, but sp can be used, just modify
// the call to setTextSize
float size = getResources().getDimensionPixelSize(R.dimen.solutions_view_max_font_size);
for (int textViewHeight = Integer.MAX_VALUE; textViewHeight > oldHeight; size -= 0.1f) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
// measure the text views size using a fixed width and an
// unspecified height - the unspecified height means measure
// returns the textviews ideal height
textView.measure(MeasureSpec.makeMeasureSpec(oldWidth, MeasureSpec.EXACTLY), MeasureSpec.UNSPECIFIED);
textViewHeight = textView.getMeasuredHeight();
}
}
}