可根据控件宽度自动改变字体大小。
package com.hcb.fixorder.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import com.hcb.base.common.util.DisplayUtils;
/**
* 字体大小自适应宽度
* ps:必须给出具体宽度才有效
*
* @author 陈聪 2020-09-03 19:10
*/
public class AutoAlignTextView extends androidx.appcompat.widget.AppCompatTextView {
public AutoAlignTextView(Context context) {
this(context, null);
}
public AutoAlignTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoAlignTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
public void init(Context context, AttributeSet attrs) {
setMaxLines(1);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
adjustTvTextSize();
}
/**
* 动态修改字体大小
*/
private void adjustTvTextSize() {
String text = getText().toString();
int avaiWidth = (int) (this.getWidth() - getPaddingLeft() - getPaddingRight() - DisplayUtils.dip2px(getContext(), 2));
if (avaiWidth <= 0) {
return;
}
TextPaint textPaintClone = new TextPaint(getPaint());
float trySize = textPaintClone.getTextSize();
if (startTxSize == 0) {
startTxSize = trySize;
} else {
trySize = startTxSize;
}
textPaintClone.setTextSize(trySize);
while (textPaintClone.measureText(text) > avaiWidth) {
trySize--;
textPaintClone.setTextSize(trySize);
}
setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
}
/** 缓存初始字体大小,防止出现字体一直变小的情况 */
private float startTxSize = 0;
public void refresh() {
adjustTvTextSize();
}
}
网友评论