I\'m looking for an optimal way to resize wrapping text in a TextView
so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for
This solutions works for us:
public class CustomFontButtonTextFit extends CustomFontButton
{
private final float DECREMENT_FACTOR = .1f;
public CustomFontButtonTextFit(Context context) {
super(context);
}
public CustomFontButtonTextFit(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomFontButtonTextFit(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
private synchronized void refitText(String text, int textWidth) {
if (textWidth > 0)
{
float availableWidth = textWidth - this.getPaddingLeft()
- this.getPaddingRight();
TextPaint tp = getPaint();
Rect rect = new Rect();
tp.getTextBounds(text, 0, text.length(), rect);
float size = rect.width();
while(size > availableWidth)
{
setTextSize( getTextSize() - DECREMENT_FACTOR );
tp = getPaint();
tp.getTextBounds(text, 0, text.length(), rect);
size = rect.width();
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
refitText(this.getText().toString(), parentWidth);
if(parentWidth < getSuggestedMinimumWidth())
parentWidth = getSuggestedMinimumWidth();
if(parentHeight < getSuggestedMinimumHeight())
parentHeight = getSuggestedMinimumHeight();
this.setMeasuredDimension(parentWidth, parentHeight);
}
@Override
protected void onTextChanged(final CharSequence text, final int start,
final int before, final int after)
{
super.onTextChanged(text, start, before, after);
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw)
refitText(this.getText().toString(), w);
}
}