Android8.0 and above
- You can add autoSizeTextType to TextView to achieve
Below Android8.0
public class PZHelp_TextView_AutoTextSize extends androidx.appcompat.widget.AppCompatTextView {
public static final String TAG = "AutoTextSize";
private int mViewWidth, mViewHeight;
private float sizeOfWidth, sizeOfHeight;
private float mMinTextSize = 10;
public PZHelp_TextView_AutoTextSize(Context context) {
super(context);
init();
}
public PZHelp_TextView_AutoTextSize(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PZHelp_TextView_AutoTextSize(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
void init() {
setGravity(Gravity.CENTER);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
changeTextSize();
}
private void changeTextSize() {
TextPaint mTextPaint = getPaint();
float mCurrentTextSize = getTextSize();
sizeOfWidth = sizeOfHeight = mCurrentTextSize;
String mCurrentText = getText().toString().trim();
float mCurrentTextWidth = mTextPaint.measureText(mCurrentText);
float mCurrentTextHeight = Math.abs(mTextPaint.descent()) + Math.abs(mTextPaint.ascent());
if (mCurrentTextWidth > mViewWidth || mCurrentTextWidth < mViewWidth * 0.8) {
float scale = mCurrentTextWidth / mCurrentTextSize;
sizeOfWidth = (float) ((mViewWidth * 0.8) / scale);
}
if (mCurrentTextHeight > mViewHeight || mCurrentTextHeight < mViewHeight * 0.8) {
float scale = mCurrentTextHeight / mCurrentTextSize;
sizeOfHeight = mViewHeight / scale;
}
float newTextSize = Math.min(sizeOfWidth, sizeOfHeight);
if (newTextSize < mMinTextSize) {
newTextSize = mMinTextSize;
}
setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSize);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mViewWidth = MeasureSpec.getSize(widthMeasureSpec);
mViewHeight = MeasureSpec.getSize(heightMeasureSpec);
}
}