前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >笔记11 | 动态设置TextView的字体大小

笔记11 | 动态设置TextView的字体大小

作者头像
项勇
发布2018-06-19 15:13:37
1.6K0
发布2018-06-19 15:13:37
举报
文章被收录于专栏:项勇

地址

CSDN地址:http://blog.csdn.net/xiangyong_1521/article/details/78137394

当需要动态更改的TextView的内容字体的大小,比如设定的TextView的只有一行,宽度只有200dp,内容超过这个之后就缩小字体显示,只能能将字体都显示完全;也就是动态更改的的TextView的字体大小,当TextView的的的内容比较多时缩小显示,当TextView的中的内容比较少时正常显示

目录

  • 图片展示
  • 方法一:重写的TextView
  • 方法二:使用框架Android的autofittextview
  • 链接

一. 图片展示

可以看出来:当文字没有填充的TextView的完全时显示的就是默认的字体,当文字能够完全填充的TextView的并且一行显示不下时,他会默认的缩小文字的字体,当文字再多时,他会默认在末尾省略。


二. 方法一:重写的TextView

此类方法是在的TextView的onTextChanged和onSizeChanged下,根据获取的TextView可容纳的宽度来计算一个靠近可容纳的最大字体宽度,从而来给TextView的设置textsize。

代码语言:javascript
复制
public class CustomTextView extends TextView {

    private static float DEFAULT_MIN_TEXT_SIZE = 1; 
    private static float DEFAULT_MAX_TEXT_SIZE = 48;

    // Attributes
    private Paint testPaint; 
    private float minTextSize, TextSize, maxTextSize;

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

    private void initialise() {
        /*
         * limited size
         */
        testPaint = new Paint();
        testPaint.set(this.getPaint());
        TextSize = this.getTextSize();
        if (TextSize <= DEFAULT_MIN_TEXT_SIZE) {
            TextSize = DEFAULT_MIN_TEXT_SIZE;
        }
        if (TextSize >= DEFAULT_MAX_TEXT_SIZE) {
            TextSize = DEFAULT_MAX_TEXT_SIZE;
        }
        minTextSize = DEFAULT_MIN_TEXT_SIZE;
        maxTextSize = DEFAULT_MAX_TEXT_SIZE;
    };

    /*
     * (non-Javadoc)
     * @see android.widget.TextView#onTextChanged(java.lang.CharSequence, int, int, int)
     */
    @Override
    protected void onTextChanged(CharSequence text, int start, int before,
            int after) {
        super.onTextChanged(text, start, before, after);
        refitText(text.toString(), this.getWidth());
    }

    /*
     * (non-Javadoc)
     * @see android.view.View#onSizeChanged(int, int, int, int)
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
        }
    }
    //修改text方法
    private void refitText(String text, int textWidth) {

        if (textWidth > 0) {
            int availableWidth = textWidth - this.getPaddingLeft()
                    - this.getPaddingRight();// 获取实际TextView的画布可用大小        
            float trySize = TextSize; 
            float scaled = getContext().getResources().getDisplayMetrics().scaledDensity*trySize; //dp转为px后的textsize
            testPaint.setTextSize(scaled);
            while ((trySize > minTextSize||trySize<maxTextSize)&& 
                    (testPaint.measureText(text) > availableWidth) 
                    ) {
                trySize -= 2; //减小2个单位大小
                FontMetrics fm = testPaint.getFontMetrics();
                float scaled1 = (float) (this.getHeight() / (Math.ceil(fm.descent - fm.top) + 2));  
                float scaled2 = (float) ((testPaint.measureText(text) / availableWidth)); 
                if (scaled1 >= 1.75 & scaled1 >= scaled2) {
                    break;
                }
                if (trySize <= minTextSize) {
                    trySize = minTextSize;
                    break;
                }else if (trySize >= maxTextSize) {
                    trySize = maxTextSize;
                    break;
                }
                testPaint.setTextSize(trySize * scaled);
            }
            this.setTextSize(trySize); 
        }
    };
}

三. 方法二:使用框架Android的autofittextview

框架地址:HTTPS://github.com/grantland/android-autofittextview

AutofitTextView:自定义的TextView的并继承系统的的TextView的,然后在绘制组件的时候根据getMaxLines方法获取内容的行数若内容的行数大于1,则缩小文字的字体,然后在尝试获取getMaxLines方法,若内容的行数还是大于1,则缩小文字的字体,直到内容能够一行显示或者是字体缩小大一定的大小,这时候若缩小到一定的大小还是不能一行显示,则尾部省略。

代码语言:javascript
复制
package me.grantland.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

/**
 * A {@link TextView} that re-sizes its text to be no larger than the width of the view.
 *
 * @attr ref R.styleable.AutofitTextView_sizeToFit
 * @attr ref R.styleable.AutofitTextView_minTextSize
 * @attr ref R.styleable.AutofitTextView_precision
 */
public class AutofitTextView extends TextView implements AutofitHelper.OnTextSizeChangeListener {

    private AutofitHelper mHelper;

    public AutofitTextView(Context context) {
        super(context);
        init(context, null, 0);
    }

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

    public AutofitTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        mHelper = AutofitHelper.create(this, attrs, defStyle)
                .addOnTextSizeChangeListener(this);
    }

    // Getters and Setters

    /**
     * {@inheritDoc}
     */
    @Override
    public void setTextSize(int unit, float size) {
        super.setTextSize(unit, size);
        if (mHelper != null) {
            mHelper.setTextSize(unit, size);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setLines(int lines) {
        super.setLines(lines);
        if (mHelper != null) {
            mHelper.setMaxLines(lines);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setMaxLines(int maxLines) {
        super.setMaxLines(maxLines);
        if (mHelper != null) {
            mHelper.setMaxLines(maxLines);
        }
    }

    /**
     * Returns the {@link AutofitHelper} for this View.
     */
    public AutofitHelper getAutofitHelper() {
        return mHelper;
    }

    /**
     * Returns whether or not the text will be automatically re-sized to fit its constraints.
     */
    public boolean isSizeToFit() {
        return mHelper.isEnabled();
    }

    /**
     * Sets the property of this field (sizeToFit), to automatically resize the text to fit its
     * constraints.
     */
    public void setSizeToFit() {
        setSizeToFit(true);
    }

    /**
     * If true, the text will automatically be re-sized to fit its constraints; if false, it will
     * act like a normal TextView.
     *
     * @param sizeToFit
     */
    public void setSizeToFit(boolean sizeToFit) {
        mHelper.setEnabled(sizeToFit);
    }

    /**
     * Returns the maximum size (in pixels) of the text in this View.
     */
    public float getMaxTextSize() {
        return mHelper.getMaxTextSize();
    }

    /**
     * Set the maximum text size to the given value, interpreted as "scaled pixel" units. This size
     * is adjusted based on the current density and user font size preference.
     *
     * @param size The scaled pixel size.
     *
     * @attr ref android.R.styleable#TextView_textSize
     */
    public void setMaxTextSize(float size) {
        mHelper.setMaxTextSize(size);
    }

    /**
     * Set the maximum text size to a given unit and value. See TypedValue for the possible
     * dimension units.
     *
     * @param unit The desired dimension unit.
     * @param size The desired size in the given units.
     *
     * @attr ref android.R.styleable#TextView_textSize
     */
    public void setMaxTextSize(int unit, float size) {
        mHelper.setMaxTextSize(unit, size);
    }

    /**
     * Returns the minimum size (in pixels) of the text in this View.
     */
    public float getMinTextSize() {
        return mHelper.getMinTextSize();
    }

    /**
     * Set the minimum text size to the given value, interpreted as "scaled pixel" units. This size
     * is adjusted based on the current density and user font size preference.
     *
     * @param minSize The scaled pixel size.
     *
     * @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize
     */
    public void setMinTextSize(int minSize) {
        mHelper.setMinTextSize(TypedValue.COMPLEX_UNIT_SP, minSize);
    }

    /**
     * Set the minimum text size to a given unit and value. See TypedValue for the possible
     * dimension units.
     *
     * @param unit The desired dimension unit.
     * @param minSize The desired size in the given units.
     *
     * @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize
     */
    public void setMinTextSize(int unit, float minSize) {
        mHelper.setMinTextSize(unit, minSize);
    }

    /**
     * Returns the amount of precision used to calculate the correct text size to fit within its
     * bounds.
     */
    public float getPrecision() {
        return mHelper.getPrecision();
    }

    /**
     * Set the amount of precision used to calculate the correct text size to fit within its
     * bounds. Lower precision is more precise and takes more time.
     *
     * @param precision The amount of precision.
     */
    public void setPrecision(float precision) {
        mHelper.setPrecision(precision);
    }

    @Override
    public void onTextSizeChange(float textSize, float oldTextSize) {
        // do nothing
    }
}

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-09-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 项勇 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 地址
    • 目录
      • 一. 图片展示
        • 二. 方法一:重写的TextView
          • 三. 方法二:使用框架Android的autofittextview
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档