textView自动缩放字体大小

来源:互联网 发布:python 模拟按键 编辑:程序博客网 时间:2024/06/05 23:48

textView显示的宽度是一定的,如果字数过长就要缩小字体,以满足显示宽度,如果字数少,就要正常显示字体大小,可自定义textView实现,代码如下:

public class AutoScaleTextView extends TextView {    private static float DEFAULT_MIN_TEXT_SIZE = 0;    private static float DEFAULT_MAX_TEXT_SIZE = 48;    private Paint testPaint;    private float minTextSize;    private float maxTextSize;    public AutoScaleTextView(Context context, AttributeSet attrs) {        super(context, attrs);        initialise();    }    private void initialise() {        testPaint = new Paint();        testPaint.set(this.getPaint());        maxTextSize = this.getTextSize();        if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {            maxTextSize = DEFAULT_MAX_TEXT_SIZE;        }        minTextSize = DEFAULT_MIN_TEXT_SIZE;    }        private void refitText(String text, int textWidth) {        if (textWidth > 0) {            int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();            float trySize = maxTextSize;            testPaint.setTextSize(trySize);            while ((trySize > minTextSize) && (testPaint.measureText(text) > availableWidth)) {                trySize -= 1;                if (trySize <= minTextSize) {                    trySize = minTextSize;                    break;                }                testPaint.setTextSize(trySize);            }            this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);//TypedValue.COMPLEX_UNIT_PX不可少,将单位设置为像素        }    }    @Override    protected void onTextChanged(CharSequence text, int start, int before, 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) {        if (w != oldw) {            refitText(this.getText().toString(), w);        }    }}


0 0
原创粉丝点击