专栏首页项勇笔记11 | 动态设置TextView的字体大小

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

地址

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。

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,则缩小文字的字体,直到内容能够一行显示或者是字体缩小大一定的大小,这时候若缩小到一定的大小还是不能一行显示,则尾部省略。

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
    }
}

本文分享自微信公众号 - 项勇(looseyouth_com)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2017-09-30

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 笔记21 | 学习整理开源APP(BaseAnimation)程序源码“中的通讯录效果(二)

    项勇
  • 使用RecyclerView的几个笔记

    方法一:重写RecyclerView.ItemDecoration 在getItemOffsets方法中设置传入的值

    项勇
  • [Android笔记7]之通过DatePickerDialog,TimePickerDialog调用系统时间设置

    项勇
  • UESTC 485 Game(康托展开,bfs打表)

    Game Time Limit: 4000/2000MS (Java/Others) Memory Limit: 65535/65535KB (Ja...

    ShenduCC
  • LeetCode Weekly Contest 38解题思路

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.n...

    用户1147447
  • UESTC 485 Game(康托,BFS)

    Today I want to introduce an interesting game to you. Like eight puzzle, it is a...

    ShenduCC
  • F2. Animal Observation (hard version)

    time limit per test:3 seconds memory limit per test:512 megabytes inputstandard ...

    某些人
  • POJ--1699 Best Sequence(DP+dfs)

    Best Sequence Time Limit: 1000MS Memory Limit: 10000K Total Submissions...

    ShenduCC
  • 06-图2 Saving James Bond - Easy Version (25分)

    This time let us consider the situation in the movie “Live and Let Die” in which...

    AI那点小事
  • 一道有趣的树状数组题

    Every year, Farmer John's N (1 <= N <= 20,000) cows attend "MooFest",a social ga...

    ACM算法日常

扫码关注云+社区

领取腾讯云代金券