zoukankan      html  css  js  c++  java
  • [转帖]自动调整TextView字体大小以适应文字长度

    package com.test.android.textview;
    
    import android.content.Context;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class CustomTextView extends TextView {
    
        private static float DEFAULT_MIN_TEXT_SIZE = 10;
        private static float DEFAULT_MAX_TEXT_SIZE = 20;
    
        // Attributes
        private Paint testPaint;
        private float minTextSize, maxTextSize;
    
        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initialise();
        }
    
        private void initialise() {
            testPaint = new Paint();
            testPaint.set(this.getPaint());
    
            // max size defaults to the intially specified text size unless it is
            // too small
            maxTextSize = this.getTextSize();
    
            if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {
                maxTextSize = DEFAULT_MAX_TEXT_SIZE;
            }
    
            minTextSize = DEFAULT_MIN_TEXT_SIZE;
        };
    
        /**
         * Re size the font so the specified text fits in the text box * assuming
         * the text box is the specified width.
         */
        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(trySize);
            }
        };
    
        @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);
            }
        }
    }
  • 相关阅读:
    Intelij根据数据库表生成实体类
    RabbitMQ(二):入门案例
    RabbitMQ(一):简介和基本概念
    Python 第十课,面向对象补足,异常处理
    Python 第九课,面向对象进阶
    Python 第七课,模块
    Python 第六课,装饰器,生成器,迭代器,其他
    Python 第五课,正则表达式
    Python 第四课,内置函数,I/O操作。
    Python 第三课,函数。
  • 原文地址:https://www.cnblogs.com/xiaorenwu702/p/4401456.html
Copyright © 2011-2022 走看看