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 大小范围内).









网友评论