33.Android 自动适配字体大小的AutoAdjustSizeEditText

33.Android 自动适配字体大小的AutoAdjustSizeEditText


AutoAdjustSizeEditText介绍

由于一个需求,就是一个定宽高的EditText里,输入后,要根据字的内容改变字体大小。

这时候就需要这么一个自定适配字体大小的EditView。


AutoAdjustSizeEditText原理

实现原理: 重写EditText,覆写其setTextonTextChangedonSizeChanged方法。分别在这里重新写适配字体大小的逻辑处理,所谓的逻辑处理,就是计算单行可见文字的宽度,然后从自定义的最大字体开始尝试,先用最大字体去写字( Paint.setTextSize(float textSize) ),然后判断:最大字体画出字的宽度>可见文字宽度。如果成立,那么减小一号字体再去画,不断去减小字体去判断,直到不成立时,就找到合适的字体大小了。


AutoAdjustSizeEditText

public class AutoAdjustSizeEditText extends EditText {

    // 最小字体
    private static final float DEFAULT_MIN_TEXT_SIZE = 8.0f;
    // 最大字体
    private static final float DEFAULT_MAX_TEXT_SIZE = 16.0f;

    private Paint textPaint;
    private float minTextSize = DEFAULT_MIN_TEXT_SIZE;
    private float maxTextSize = DEFAULT_MAX_TEXT_SIZE;

    public AutoAdjustSizeEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private void initialise() {
        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
        if (this.textPaint == null) {
            this.textPaint = new Paint();
            this.textPaint.set(this.getPaint());
        }
        this.maxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.maxTextSize, displayMetrics);
        if (DEFAULT_MIN_TEXT_SIZE >= maxTextSize) {
            this.maxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.maxTextSize, displayMetrics);
        }
        this.maxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.maxTextSize, displayMetrics);
        this.minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.minTextSize, displayMetrics);
    }

    /**
     * Re size the font so the specified text fits in the text box * assuming
     * the text box is the specified width.
     */
    private void fitText(String text, int textWidth) {
        if (textWidth > 0) {
            // 单行可见文字宽度
            int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
            float trySize = maxTextSize;
            // 先用最大字体写字
            textPaint.setTextSize(trySize);
            // 如果最大字体>最小字体 && 最大字体画出字的宽度>单行可见文字宽度
            while ((trySize > minTextSize) && (textPaint.measureText(text) > availableWidth)) {
                // 最大字体小一号
                trySize -= 1;
                // 保证大于最小字体
                if (trySize <= minTextSize) {
                    trySize = minTextSize;
                    break;
                }
                // 再次用新字体写字
                textPaint.setTextSize(trySize);
            }
            this.setTextSize(trySize);
        }
    }


    /**
     * 重写setText
     * 每次setText的时候
     *
     * @param text
     * @param type
     */
    @Override
    public void setText(CharSequence text, BufferType type) {
        this.initialise();
        String textString = text.toString();
        float trySize = maxTextSize;
        if (this.textPaint == null) {
            this.textPaint = new Paint();
            this.textPaint.set(this.getPaint());
        }
        this.textPaint.setTextSize(trySize);
        // 计算设置内容前 内容占据的宽度
        int textWidth = (int) this.textPaint.measureText(textString);
        // 拿到宽度和内容,进行调整
        this.fitText(textString, textWidth);
        super.setText(text, type);
    }


    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        super.onTextChanged(text, start, before, after);
        this.fitText(text.toString(), this.getWidth());
    }


    /**
     * This is called during layout when the size of this view has changed. If
     * you were just added to the view hierarchy, you're called with the old
     * values of 0.
     *
     * @param w    Current width of this view.
     * @param h    Current height of this view.
     * @param oldw Old width of this view.
     * @param oldh Old height of this view.
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // 如果当前view的宽度 != 原来view的宽度
        if (w != oldw) this.fitText(this.getText().toString(), w);
    }


}

AutoAdjustSizeEditTextActivity

AutoAdjustSizeEditTextActivity

public class AutoAdjustSizeEditTextActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_auto_adjust_size_edit_text);
    }
}

activity_auto_adjust_size_edit_text.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <camnter.newlife.widget.AutoAdjustSizeEditText
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything"
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeEditText
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything"
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeEditText
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything Save you from anything "
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeEditText
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything Save you from anything Save you from anything "
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeEditText
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything Save you from anything Save you from anything Save you from anything "
        android:textColor="#ffFF4081" />


</LinearLayout>

AutoAdjustSizeEditTextActivity效果图

AutoAdjustSizeEditText


AutoAdjustSizeTextView

由于,EditText也是TextView的子类,所以用上面的AutoAdjustSizeEditText代码一样可以实现自动适配字体大小的TextView。

public class AutoAdjustSizeTextView extends TextView {

    // 最小字体
    private static final float DEFAULT_MIN_TEXT_SIZE = 8.0f;
    // 最大字体
    private static final float DEFAULT_MAX_TEXT_SIZE = 16.0f;

    private Paint textPaint;
    private float minTextSize = DEFAULT_MIN_TEXT_SIZE;
    private float maxTextSize = DEFAULT_MAX_TEXT_SIZE;

    public AutoAdjustSizeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private void initialise() {
        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
        if (this.textPaint == null) {
            this.textPaint = new Paint();
            this.textPaint.set(this.getPaint());
        }
        this.maxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.maxTextSize, displayMetrics);
        if (DEFAULT_MIN_TEXT_SIZE >= maxTextSize) {
            this.maxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.maxTextSize, displayMetrics);
        }
        this.maxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.maxTextSize, displayMetrics);
        this.minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.minTextSize, displayMetrics);
    }

    /**
     * Re size the font so the specified text fits in the text box * assuming
     * the text box is the specified width.
     */
    private void fitText(String text, int textWidth) {
        if (textWidth > 0) {
            // 单行可见文字宽度
            int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
            float trySize = maxTextSize;
            // 先用最大字体写字
            textPaint.setTextSize(trySize);
            // 如果最大字体>最小字体 && 最大字体画出字的宽度>单行可见文字宽度
            while ((trySize > minTextSize) && (textPaint.measureText(text) > availableWidth)) {
                // 最大字体小一号
                trySize -= 1;
                // 保证大于最小字体
                if (trySize <= minTextSize) {
                    trySize = minTextSize;
                    break;
                }
                // 再次用新字体写字
                textPaint.setTextSize(trySize);
            }
            this.setTextSize(trySize);
        }
    }


    /**
     * 重写setText
     * 每次setText的时候
     *
     * @param text
     * @param type
     */
    @Override
    public void setText(CharSequence text, BufferType type) {
        this.initialise();
        String textString = text.toString();
        float trySize = maxTextSize;
        if (this.textPaint == null) {
            this.textPaint = new Paint();
            this.textPaint.set(this.getPaint());
        }
        this.textPaint.setTextSize(trySize);
        // 计算设置内容前 内容占据的宽度
        int textWidth = (int) this.textPaint.measureText(textString);
        // 拿到宽度和内容,进行调整
        this.fitText(textString, textWidth);
        super.setText(text, type);
    }


    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        super.onTextChanged(text, start, before, after);
        this.fitText(text.toString(), this.getWidth());
    }


    /**
     * This is called during layout when the size of this view has changed. If
     * you were just added to the view hierarchy, you're called with the old
     * values of 0.
     *
     * @param w    Current width of this view.
     * @param h    Current height of this view.
     * @param oldw Old width of this view.
     * @param oldh Old height of this view.
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // 如果当前view的宽度 != 原来view的宽度
        if (w != oldw) this.fitText(this.getText().toString(), w);
    }


}

AutoAdjustSizeTextViewActivity

AutoAdjustSizeTextViewActivity

public class AutoAdjustSizeTextViewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_auto_adjust_size_text_view);
    }
}

activity_auto_adjust_size_text_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <camnter.newlife.widget.AutoAdjustSizeTextView
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything"
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeTextView
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything"
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeTextView
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything Save you from anything "
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeTextView
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything Save you from anything Save you from anything "
        android:textColor="#ffFF4081" />

    <camnter.newlife.widget.AutoAdjustSizeTextView
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:padding="16dp"
        android:text="Save you from anything Save you from anything Save you from anything Save you from anything Save you from anything "
        android:textColor="#ffFF4081" />


</LinearLayout>

AutoAdjustSizeTextViewActivity效果图

AutoAdjustSizeTextView

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值