Android动态更改TextView的字体大小

需求:

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

使用框架:Android-autofittextview
地址:https://github.com/grantland/android-autofittextview

使用方式详见官网介绍。

例子展示:

这里写图片描述

这里写图片描述

这里写图片描述

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


AutofitTextView.java代码:

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

原理:

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

延伸:
TextView源码中:

public void setTextSize(float size) {
        setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
    }
public void setTextSize(int unit, float size) {
        Context c = getContext();
        Resources r;

        if (c == null)
            r = Resources.getSystem();
        else
            r = c.getResources();

        setRawTextSize(TypedValue.applyDimension(
                unit, size, r.getDisplayMetrics()));
    }

setTextSize(int unit, int size)
第一个参数可设置如下静态变量:
TypedValue.COMPLEX_UNIT_PX : Pixels
TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels

我们在使用TextView控件时,调用setTextSize方法,默认就是以sp为单位,与xml配置文件默认保存一致。

参考:http://blog.csdn.net/qq_23547831/article/details/50592352

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要在Android Studio中设置TextView字体大小,可以通过以下步骤完成: 1. 在布局文件中找到要设置字体大小TextView。 2. 在TextView标签中添加以下属性:android:textSize="字体大小"。例如,要将字体大小设置为16sp,可以添加以下属性:android:textSize="16sp"。 3. 保存并运应用程序,查看TextView字体大小是否已更改。 希望这可以帮助您设置TextView字体大小。 ### 回答2: 在Android Studio中,TextView是用来显示文本和可选图像的类。TextView可以显示不同大小的文本,而Android Studio提供了多种方法来设置TextView字体大小。 1. 在XML中设置 TextView 字体大小 您可以通过在XML布局文件中设置textSize属性来设置TextView字体大小。例如:<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textSize="20sp"/> 2. 通过编程设置 TextView 字体大小 您也可以在Java代码中设置TextView字体大小。例如: TextView textView = (TextView)findViewById(R.id.textView1); textView.setTextSize(20); 3. 使用 Dimension 类设置 TextView 字体大小 如果您想要动态计算TextView字体大小,您可以使用Dimension类来定义字体大小并在Java代码中设置它。例如: int fontSize = getResources().getDimensionPixelSize(R.dimen.font_size); TextView textView = (TextView)findViewById(R.id.textView1); textView.setTextSize(fontSize); 4. 使用 Styles 和 Themes 设置 TextView 字体大小 您可以使用样式和主题来设置TextView字体大小。您可以创建一个样式和主题,然后将其应用到您的TextView中。例如: - 在styles.xml文件中创建一个样式: <style name="LargeText"> <item name="android:textSize">20sp</item> </style> - 在themes.xml文件中创建一个主题: <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="textViewStyle">@style/LargeText</item> </style> - 将主题应用到Activity或应用程序的Manifest文件中: <activity android:name=".MainActivity" android:theme="@style/AppTheme"/> 综上所述,通过以上四种方法,您可以轻松设置TextView字体大小。您可以选择最适合您需求的方法来设置您的TextView。 ### 回答3: 在Android Studio中,我们可以通过设置TextView字体大小来控制文本展示的大小。使用TextView时,我们可以使用以下两种方式来设置其字体大小: 1.在布局文件中设置字体大小: 我们可以在布局文件中通过使用“android:textSize”属性来设置文本的字体大小。例如,下面的代码将设置TextView字体大小为16sp: ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:text="Hello World!" /> ``` 2.在代码中设置字体大小: 我们还可以在代码中动态地设置TextView字体大小。可以使用“setTextSize()”方法来设置字体大小。例如,下面的代码将设置TextView字体大小为18sp: ``` TextView textView = findViewById(R.id.textView); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); ``` 其中,TypedValue.COMPLEX_UNIT_SP表示设置字体大小的单位为“sp”(缩放独立像素)。 除了上述两种设置字体大小的方式,我们还可以通过使用样式(style)来设置TextView字体大小。在这种情况下,我们需要在样式中设置“android:textSize”属性,然后将样式应用到TextView中。下面的样式将设置TextView字体大小为20sp: ``` <style name="MyTextViewStyle"> <item name="android:textSize">20sp</item> </style> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/MyTextViewStyle" android:text="Hello World!" /> ``` 总之,在Android Studio中设置TextView字体大小非常简单。我们可以在布局文件中设置,也可以在代码中动态设置,还可以使用样式来进设置。根据不同的需求,我们可以选择适合的方式来设置字体大小
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值