笔记11 | 动态更改TextView的字体大小

本文介绍了两种动态改变Android中TextView字体大小的方法。方法一是通过重写TextView,在`onTextChanged`和`onSizeChanged`事件中计算合适的字体大小。方法二是使用第三方库AutofitTextView,它会自动根据TextView宽度和内容调整字体,当内容过多时进行省略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

地址


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

目录

  • 图片展示

  • 方法一:重写的TextView

  • 方法二:使用框架Android的autofittextview


图片展示

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


方法一:重写的TextView

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

public class CustomTextView extends TextView {
	
	/*
	 * Even add it by 20170518 
	 * dynamic setting textview's width and textsize Demo
	 * 
	 */
	
	/*
	 * 定义字体大小边界值
	 */
	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);
		}
	}
	
	private void refitText(String text, int textWidth) {

		if (textWidth > 0) {
			int availableWidth = textWidth - this.getPaddingLeft()
					- this.getPaddingRight();       
			float trySize = TextSize; 
			float scaled = getContext().getResources().getDisplayMetrics().scaledDensity;
			testPaint.setTextSize(trySize * scaled);//给testPaint设置 dp转为px后的textsize
			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,则缩小文字的字体,直到内容能够一行显示或者是字体缩小大一定的大小,这时候若缩小到一定的大小还是不能一行显示,则尾部省略。

  1. package me.grantland.widget;

  2. import android.content.Context;

  3. import android.util.AttributeSet;

  4. import android.util.TypedValue;

  5. import android.widget.TextView;

  6. /**

  7. * A {@link TextView} that re-sizes its text to be no larger than the width of the view.

  8. *

  9. * @attr ref R.styleable.AutofitTextView_sizeToFit

  10. * @attr ref R.styleable.AutofitTextView_minTextSize

  11. * @attr ref R.styleable.AutofitTextView_precision

  12. */

  13. public class AutofitTextView extends TextView implements AutofitHelper.OnTextSizeChangeListener {

  14.    private AutofitHelper mHelper;

  15.    public AutofitTextView(Context context) {

  16.        super(context);

  17.        init(context, null, 0);

  18.    }

  19.    public AutofitTextView(Context context, AttributeSet attrs) {

  20.        super(context, attrs);

  21.        init(context, attrs, 0);

  22.    }

  23.    public AutofitTextView(Context context, AttributeSet attrs, int defStyle) {

  24.        super(context, attrs, defStyle);

  25.        init(context, attrs, defStyle);

  26.    }

  27.    private void init(Context context, AttributeSet attrs, int defStyle) {

  28.        mHelper = AutofitHelper.create(this, attrs, defStyle)

  29.                .addOnTextSizeChangeListener(this);

  30.    }

  31.    // Getters and Setters

  32.    /**

  33.     * {@inheritDoc}

  34.     */

  35.    @Override

  36.    public void setTextSize(int unit, float size) {

  37.        super.setTextSize(unit, size);

  38.        if (mHelper != null) {

  39.            mHelper.setTextSize(unit, size);

  40.        }

  41.    }

  42.    /**

  43.     * {@inheritDoc}

  44.     */

  45.    @Override

  46.    public void setLines(int lines) {

  47.        super.setLines(lines);

  48.        if (mHelper != null) {

  49.            mHelper.setMaxLines(lines);

  50.        }

  51.    }

  52.    /**

  53.     * {@inheritDoc}

  54.     */

  55.    @Override

  56.    public void setMaxLines(int maxLines) {

  57.        super.setMaxLines(maxLines);

  58.        if (mHelper != null) {

  59.            mHelper.setMaxLines(maxLines);

  60.        }

  61.    }

  62.    /**

  63.     * Returns the {@link AutofitHelper} for this View.

  64.     */

  65.    public AutofitHelper getAutofitHelper() {

  66.        return mHelper;

  67.    }

  68.    /**

  69.     * Returns whether or not the text will be automatically re-sized to fit its constraints.

  70.     */

  71.    public boolean isSizeToFit() {

  72.        return mHelper.isEnabled();

  73.    }

  74.    /**

  75.     * Sets the property of this field (sizeToFit), to automatically resize the text to fit its

  76.     * constraints.

  77.     */

  78.    public void setSizeToFit() {

  79.        setSizeToFit(true);

  80.    }

  81.    /**

  82.     * If true, the text will automatically be re-sized to fit its constraints; if false, it will

  83.     * act like a normal TextView.

  84.     *

  85.     * @param sizeToFit

  86.     */

  87.    public void setSizeToFit(boolean sizeToFit) {

  88.        mHelper.setEnabled(sizeToFit);

  89.    }

  90.    /**

  91.     * Returns the maximum size (in pixels) of the text in this View.

  92.     */

  93.    public float getMaxTextSize() {

  94.        return mHelper.getMaxTextSize();

  95.    }

  96.    /**

  97.     * Set the maximum text size to the given value, interpreted as "scaled pixel" units. This size

  98.     * is adjusted based on the current density and user font size preference.

  99.     *

  100.     * @param size The scaled pixel size.

  101.     *

  102.     * @attr ref android.R.styleable#TextView_textSize

  103.     */

  104.    public void setMaxTextSize(float size) {

  105.        mHelper.setMaxTextSize(size);

  106.    }

  107.    /**

  108.     * Set the maximum text size to a given unit and value. See TypedValue for the possible

  109.     * dimension units.

  110.     *

  111.     * @param unit The desired dimension unit.

  112.     * @param size The desired size in the given units.

  113.     *

  114.     * @attr ref android.R.styleable#TextView_textSize

  115.     */

  116.    public void setMaxTextSize(int unit, float size) {

  117.        mHelper.setMaxTextSize(unit, size);

  118.    }

  119.    /**

  120.     * Returns the minimum size (in pixels) of the text in this View.

  121.     */

  122.    public float getMinTextSize() {

  123.        return mHelper.getMinTextSize();

  124.    }

  125.    /**

  126.     * Set the minimum text size to the given value, interpreted as "scaled pixel" units. This size

  127.     * is adjusted based on the current density and user font size preference.

  128.     *

  129.     * @param minSize The scaled pixel size.

  130.     *

  131.     * @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize

  132.     */

  133.    public void setMinTextSize(int minSize) {

  134.        mHelper.setMinTextSize(TypedValue.COMPLEX_UNIT_SP, minSize);

  135.    }

  136.    /**

  137.     * Set the minimum text size to a given unit and value. See TypedValue for the possible

  138.     * dimension units.

  139.     *

  140.     * @param unit The desired dimension unit.

  141.     * @param minSize The desired size in the given units.

  142.     *

  143.     * @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize

  144.     */

  145.    public void setMinTextSize(int unit, float minSize) {

  146.        mHelper.setMinTextSize(unit, minSize);

  147.    }

  148.    /**

  149.     * Returns the amount of precision used to calculate the correct text size to fit within its

  150.     * bounds.

  151.     */

  152.    public float getPrecision() {

  153.        return mHelper.getPrecision();

  154.    }

  155.    /**

  156.     * Set the amount of precision used to calculate the correct text size to fit within its

  157.     * bounds. Lower precision is more precise and takes more time.

  158.     *

  159.     * @param precision The amount of precision.

  160.     */

  161.    public void setPrecision(float precision) {

  162.        mHelper.setPrecision(precision);

  163.    }

  164.    @Override

  165.    public void onTextSizeChange(float textSize, float oldTextSize) {

  166.        // do nothing

  167.    }

  168. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值