美文网首页
Android TextView 设置文本 自动调整大小 - 源

Android TextView 设置文本 自动调整大小 - 源

作者: 行走中的3卡 | 来源:发表于2022-12-08 11:55 被阅读0次

TextView 的文本内容,可以提供多种语言翻译。
例如中文 和 英文, 设置同个字体大小, 可能在中文下显示不全等.

TextView 提供 API:setAutoSizeTextTypeUniformWithConfiguration
可以做到根据文本内容 去 动态 自动调整大小

1. 简单使用

样例:

textView1.setAutoSizeTextTypeUniformWithConfiguration(1, 300, 1, TypedValue.COMPLEX_UNIT_PX);

第一个参数是最小值,第二个参数是最大值, 知道这两个即可.

2. 源码分析

2.1 setAutoSizeTextTypeUniformWithConfiguration

package android.widget;

@RemoteView
public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {

    public void setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize,
            int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit) {
        if (supportsAutoSizeText()) {
            ...

            if (setupAutoSizeText()) {
                autoSizeText();
                invalidate();
            }
        }

分析:
(1) 第一个参数是最小值, 第二个参数是最大值
(2) supportsAutoSizeText() 在TextView 里返回值是true
(3) 重点是 autoSizeText() , 它会设置一个合适的值

2.2 autoSizeText 源码

    private void autoSizeText() {
                ...
                final float optimalTextSize = findLargestTextSizeWhichFits(TEMP_RECTF);

                if (optimalTextSize != getTextSize()) {
                    setTextSizeInternal(TypedValue.COMPLEX_UNIT_PX, optimalTextSize,
                            false /* shouldRequestLayout */);         
                ...

可以看出,
(1)调用findLargestTextSizeWhichFits 找到一个新的大小值 optimalTextSize
(2) optimalTextSize 与现在的字体大小比较, 不同则重新设置

2.3 findLargestTextSizeWhichFits 源码

核心代码

    /**
     * Performs a binary search to find the largest text size that will still fit within the size
     * available to this view.
     */
    private int findLargestTextSizeWhichFits(RectF availableSpace) {
        final int sizesCount = mAutoSizeTextSizesInPx.length;
        if (sizesCount == 0) {
            throw new IllegalStateException("No available text sizes to choose from.");
        }

        int bestSizeIndex = 0;
        int lowIndex = bestSizeIndex + 1;
        int highIndex = sizesCount - 1;
        int sizeToTryIndex;
        while (lowIndex <= highIndex) {
            sizeToTryIndex = (lowIndex + highIndex) / 2;
            if (suggestedSizeFitsInSpace(mAutoSizeTextSizesInPx[sizeToTryIndex], availableSpace)) {
                bestSizeIndex = lowIndex;
                lowIndex = sizeToTryIndex + 1;
            } else {
                highIndex = sizeToTryIndex - 1;
                bestSizeIndex = highIndex;
            }
        }

        return mAutoSizeTextSizesInPx[bestSizeIndex];
    }

可以看出,它是在一个数组里, 通过二分查找, 找到最合适的大小值并返回(在TextView 大小范围内).

相关文章

网友评论

      本文标题:Android TextView 设置文本 自动调整大小 - 源

      本文链接:https://www.haomeiwen.com/subject/lfwnfdtx.html