public class SingleLineTextView extends AppCompatTextView {
private Paint mTextPaint;
private float mTextSize;
public SingleLineTextView(Context context) {
this(context, null);
}
public SingleLineTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SingleLineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
refitText(this.getText().toString(), this.getWidth());
}
private void refitText(String text, int textViewWidth) {
if (text == null || textViewWidth <= 0)
return;
mTextPaint = getPaint();
mTextSize = getTextSize();
int availableTextViewWidth = textViewWidth - getPaddingLeft() - getPaddingRight();
float textMeausreWith = mTextPaint.measureText(text);
if (textMeausreWith > availableTextViewWidth) {
mTextSize = mTextSize * ((float) availableTextViewWidth / textMeausreWith);
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
}
}