Skip to content

Instantly share code, notes, and snippets.

@cab404
Created November 22, 2016 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cab404/7b8a4217d731894f9ee5deabed59532b to your computer and use it in GitHub Desktop.
Save cab404/7b8a4217d731894f9ee5deabed59532b to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Width resizing text view
*
* @author cab404
*/
public class WidthResizeTextView extends TextView {
public WidthResizeTextView(Context context) {
super(context);
}
public WidthResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WidthResizeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
setSingleLine();
}
float lastWidth, lastCalculatedSize;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int viewWidth = getWidth();
float top = viewWidth, bottom = 0, width = 0, current = 0;
int spec = MeasureSpec.makeMeasureSpec(1000000, MeasureSpec.AT_MOST);
int steps = 300;
if (viewWidth != lastWidth) {
while (Math.abs(width - viewWidth) > 5f && steps-- > 0) {
current = (top + bottom) / 2;
setTextSize(current);
measure(spec, spec);
width = getMeasuredWidth();
if (width - viewWidth < 0)
bottom = (top - bottom) / 2 + bottom;
if (width - viewWidth > 0)
top = top - (top - bottom) / 2;
}
lastWidth = viewWidth;
lastCalculatedSize = current;
} else {
current = lastCalculatedSize;
}
setTextSize(current);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment