自适应大小的TextView

序言

有些时候,一个控件文字内容太多,需要其自动缩小字体。开发了这个自定义控件。

效果

在这里插入图片描述

源码

只需要像普通TextView那样使用就行了。需要注意。控件需要明确的宽高。否则无法判断是否需要缩放字体。
注意,通过在xml中设置maxLines可以限制AutoResizeTextView 显示的行数

package com.trs.app.autosizetextview2;

import android.content.Context;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;

/**
 * <pre>
 * Created by zhuguohui
 * Date: 2024/1/25
 * Time: 10:14
 * Desc:
 * </pre>
 */
public class AutoResizeTextView extends androidx.appcompat.widget.AppCompatTextView {

    private TextPaint textPaint;
    private float originalTextSize;

    public AutoResizeTextView(Context context) {
        super(context);
        init();
    }

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

    private void init() {
        textPaint = new TextPaint();
        textPaint.set(this.getPaint());
        originalTextSize = this.getTextSize();
    }

    private void resizeText() {
        if (getWidth() <= 0 || getHeight() <= 0) {
            return;
        }

        float bestTextSize = getBestSize(0, originalTextSize);

        this.setTextSize(TypedValue.COMPLEX_UNIT_PX,bestTextSize);
    }

    private float getBestSize(float start, float end) {
        float precision = 0.5f;
        float target=end;
        if(isAllTextDisplayed(target)){
            return target;
        }
        while ((target - start) > precision) {
            target-=precision;
            if (isAllTextDisplayed(target)) {
               return target;
            }
        }

        return target;
    }

    //文字是否全部显示
    private boolean isAllTextDisplayed(float textSize) {
        textPaint.setTextSize(textSize);
        StaticLayout layout = new StaticLayout(getText(), textPaint, getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        int maxLines = getMaxLines();
        int lineCount = layout.getLineCount();
        return (lineCount<=maxLines)&&(layout.getHeight() <= getHeight());
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        super.onTextChanged(text, start, before, after);
        resizeText();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != oldw || h != oldh) {
            resizeText();
        }
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        resizeText();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值