大家可能都會遇到這樣一個設(shè)計:某個界面設(shè)計有個ShowMore按鈕枯途,點擊是文本的展開與收縮酪夷。Android默認的效果大家可能都會通過setMaxLines來實現(xiàn)晚岭,但直接這么做是沒有動畫的坦报,就是一個文本的突變片择。很早之前也想過要實現(xiàn)一個動畫字管,但對TextView的Layout不熟悉就一直沒做過。最近在一次CodeReview的時候亡呵,iOS實現(xiàn)了這個效果锰什,這不行啊汁胆,我們Android不能落后啊嫩码。所以最后作出了下面的效果谢谦。
基本是完整兼容TextView本身。收縮小圖有...猩谊,而且這個點點還是TextView本身的實現(xiàn)牌捷,沒做過任何修改暗甥。
不關(guān)心原理可以直接使用TextViewUtils
https://github.com/aesean/ActivityStack/blob/master/app/src/main/java/com/aesean/activitystack/utils/TextViewUtils.java
使用方法很簡單:
int lines = mTextView.getMaxLines() == 3 ? Integer.MAX_VALUE : 3;
mTextView.setMaxLineWithAnimation(lines);
但其實比起代碼本身來說撤防,實現(xiàn)代碼的過程更加重要寄月。
AutoSizeTextView
第一次看到這個效果的話漾肮,我們先思考下克懊,如何實現(xiàn)這個效果耕蝉?但就動畫來說就是TextView的高度從3行的高度變到了最大行的高度垒在。如果我們能拿到這兩個高度的話场躯,結(jié)合ValueAnimator應(yīng)該大致可以做到這個效果踢关。那問題來了怎么拿到3行或者多行的文字高度签舞?拿View本身的高度嗎儒搭?那就麻煩了搂鲫,那樣必須先繪制View然后才能拿到磺平,但我們顯然是想要在設(shè)置前就知道這個高度的擦酌。麻煩了菠劝,簡單看下TextView實現(xiàn)會發(fā)現(xiàn)锯岖,TextView會通過Layout來測量文本位置出吹,代碼非常復(fù)雜捶牢。我不是很熟悉TextView的繪制和Layout秋麸。所以雖然簡單瀏覽了還是對測量TextView高度毫無頭緒灸蟆。
怎么辦可缚?不知道有沒有人知道帘靡,Android O時候Google讓TextView實現(xiàn)了類似iOS上的自動改變文字大小的功能描姚。
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html
看到這個有沒有什么靈感?雖然沒有看過具體實現(xiàn)朝扼,但猜測這里的AutoSize擎颖,應(yīng)該是需要對文本進行測量的搂捧,不斷用不同字號,對文本進行測量搪柑,直到測量到合適的字號工碾,然后設(shè)置况木。
猜測歸猜測,我們實際去看下具體實現(xiàn)求类。不用想具體實現(xiàn)應(yīng)該在AppCompatTextView類中尸疆。
然后很容易找到三個setAutoSizeText開頭的方法和一個AppCompatTextHelper
private final AppCompatTextHelper mTextHelper;
public void setAutoSizeTextTypeWithDefaults
public void setAutoSizeTextTypeUniformWithConfiguration
public void setAutoSizeTextTypeUniformWithPresetSizes
這三個方法都是調(diào)用類AppCompatTextHelper中對應(yīng)的方法。跟到AppCompatTextHelper很容易就找到了AppCompatTextViewAutoSizeHelper
class AppCompatTextHelper {
private final @NonNull AppCompatTextViewAutoSizeHelper mAutoSizeTextHelper;
大致瀏覽下這個類會發(fā)現(xiàn)這樣一個方法
/**
* Automatically computes and sets the text size.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
void autoSizeText() {
if (!isAutoSizeEnabled()) {
return;
}
if (mNeedsAutoSizeText) {
if (mTextView.getMeasuredHeight() <= 0 || mTextView.getMeasuredWidth() <= 0) {
return;
}
final boolean horizontallyScrolling = invokeAndReturnWithDefault(
mTextView, "getHorizontallyScrolling", false);
final int availableWidth = horizontallyScrolling
? VERY_WIDE
: mTextView.getMeasuredWidth() - mTextView.getTotalPaddingLeft()
- mTextView.getTotalPaddingRight();
final int availableHeight = mTextView.getHeight() - mTextView.getCompoundPaddingBottom()
- mTextView.getCompoundPaddingTop();
if (availableWidth <= 0 || availableHeight <= 0) {
return;
}
synchronized (TEMP_RECTF) {
TEMP_RECTF.setEmpty();
TEMP_RECTF.right = availableWidth;
TEMP_RECTF.bottom = availableHeight;
final float optimalTextSize = findLargestTextSizeWhichFits(TEMP_RECTF);
if (optimalTextSize != mTextView.getTextSize()) {
setTextSizeInternal(TypedValue.COMPLEX_UNIT_PX, optimalTextSize);
}
}
}
// Always try to auto-size if enabled. Functions that do not want to trigger auto-sizing
// after the next layout pass should set this to false.
mNeedsAutoSizeText = true;
}
自動計算和設(shè)置文本大小〉鼐冢看到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];
}
大致意思就是二分搜索找到可用的最大文本大小。其實不看注釋,只看方法名字也能明白瓦灶。方法實現(xiàn)也很簡單鸠删,while循環(huán),二分搜索查找合適的大小贼陶。
private boolean suggestedSizeFitsInSpace(int suggestedSizeInPx, RectF availableSpace) {
final CharSequence text = mTextView.getText();
final int maxLines = Build.VERSION.SDK_INT >= 16 ? mTextView.getMaxLines() : -1;
if (mTempTextPaint == null) {
mTempTextPaint = new TextPaint();
} else {
mTempTextPaint.reset();
}
mTempTextPaint.set(mTextView.getPaint());
mTempTextPaint.setTextSize(suggestedSizeInPx);
// Needs reflection call due to being private.
Layout.Alignment alignment = invokeAndReturnWithDefault(
mTextView, "getLayoutAlignment", Layout.Alignment.ALIGN_NORMAL);
final StaticLayout layout = Build.VERSION.SDK_INT >= 23
? createStaticLayoutForMeasuring(
text, alignment, Math.round(availableSpace.right), maxLines)
: createStaticLayoutForMeasuringPre23(
text, alignment, Math.round(availableSpace.right));
// Lines overflow.
if (maxLines != -1 && (layout.getLineCount() > maxLines
|| (layout.getLineEnd(layout.getLineCount() - 1)) != text.length())) {
return false;
}
// Height overflow.
if (layout.getHeight() > availableSpace.bottom) {
return false;
}
return true;
}
通過調(diào)用suggestedSizeFitsInSpace方法來判斷大小是否合適刃泡,最終找到最合適的大小〉镎看到中間的StaticLayout了嗎烘贴?
final StaticLayout layout = Build.VERSION.SDK_INT >= 23
? createStaticLayoutForMeasuring(
text, alignment, Math.round(availableSpace.right), maxLines)
: createStaticLayoutForMeasuringPre23(
text, alignment, Math.round(availableSpace.right));
StaticLayout可以用來對文本進行排版測量。這個方法最后很明顯就是通過StaticLayout的測量結(jié)果和實際可繪制的大小進行比對來判斷是否合適的撮胧。
// Lines overflow.
if (maxLines != -1 && (layout.getLineCount() > maxLines
|| (layout.getLineEnd(layout.getLineCount() - 1)) != text.length())) {
return false;
}
// Height overflow.
if (layout.getHeight() > availableSpace.bottom) {
return false;
}
return true;
OK到這里AutoSizeTextView基本原理就清楚了桨踪。那對于我們上面的效果有什么幫助呢纳账?
幫助大了,我們可以順著Google的思路,也創(chuàng)建出一個StaticLayout然后我們就可以自由的計算任意文字在指定TextView上的繪制出的大小了。拿到大小后,動畫就非常簡單了棒旗。通過ValueAnimator不斷改變View的heigh來實現(xiàn)展開和收攏動畫老速。
@Nullable
public static ValueAnimator setMaxLinesWithAnimation(@NotNull final TextView textView, final int maxLine) {
measureTextHeight(textView, textView.getText().toString());
final int textHeight = measureTextHeight(textView, textView.getText(), maxLine);
if (textHeight < 0) {
// measure failed. setMaxLines directly.
textView.setMaxLines(maxLine);
return null;
}
final int minLines = textView.getMinLines();
final int targetHeight = textHeight + textView.getCompoundPaddingBottom() + textView.getCompoundPaddingTop();
return animatorToHeight(textView, targetHeight, new AnimatorListenerAdapter() {
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
}
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
textView.setMinLines(minLines);
textView.setMaxLines(maxLine);
}
});
}
@Nullable
public static ValueAnimator animatorToHeight(@NotNull final TextView textView, int h, @Nullable Animator.AnimatorListener listener) {
final int height = textView.getHeight();
if (height == h) {
return null;
}
ValueAnimator valueAnimator = new ValueAnimator();
valueAnimator.setIntValues(height, h);
long duration = makeDuration(h, height);
valueAnimator.setDuration(duration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (int) animation.getAnimatedValue();
textView.setHeight(value);
}
});
if (listener != null) {
valueAnimator.addListener(listener);
}
valueAnimator.start();
return valueAnimator;
}
但是一定注意在動畫結(jié)束后手動恢復(fù)MinLines和MaxLines
,不恢復(fù)會怎樣呢?這里我就不解釋了,你可以自己實際嘗試下,看會導(dǎo)致什么問題鹉动。
最終代碼就是:https://github.com/aesean/ActivityStack/blob/master/app/src/main/java/com/aesean/activitystack/utils/TextViewUtils.java
200多行边琉,不算多。下面代碼和github完全一致方便404用戶砍鸠。創(chuàng)建StaticLayout部分的代碼都來自AppCompatTextViewAutoSizeHelper双饥,修修補補就變成了下面的類苍匆。Google在構(gòu)建StaticLayout時候反射了部分TextView方法民轴,雖然都在說不推薦反射微驶,但既然Google都用了反射那肯定是有原因的,而且Google用了MethodCacheMap做了Method緩存降低了反射對性能的影響款筑,反射時候用defaultValue來處理反射失敗的情況。你可以嘗試將反射部分的代碼改成下面的代碼來測試反射失敗的情況限煞。
private static <T> T invokeAndReturnWithDefault(@NonNull Object object, @NonNull final String methodName, @NonNull final T defaultValue) {
if (1 == 1) {
return defaultValue;
}
}
@SuppressLint("PrivateApi")
@Nullable
private static Method getTextViewMethod(@NonNull final String methodName) {
if (1 == 1) {
return null;
}
}
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextDirectionHeuristic;
import android.text.TextDirectionHeuristics;
import android.text.TextPaint;
import android.util.Log;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Method;
import java.util.Hashtable;
/**
* TextViewUtils.
* {@link android.support.v7.widget.AppCompatTextViewAutoSizeHelper}
*
* @author danny
* @version 1.0
* @since 1/17/18
*/
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class TextViewUtils {
private static final String TAG = "TextViewUtils";
private static Hashtable<String, Method> sTextViewMethodByNameCache = new Hashtable<>();
private static final long DURATION = 600; // ms
private static final long MIN_DURATION = 100; // ms
private static final long MAX_DURATION = 1000; // ms
private static final long BASE_HEIGHT = 1000; // px
// horizontal scrolling is activated.
private static final int VERY_WIDE = 1024 * 1024;
private static RectF TEMP_RECT_F = new RectF();
private static TextPaint sTempTextPaint;
@Nullable
public static ValueAnimator setMaxLinesWithAnimation(@NotNull final TextView textView, final int maxLine) {
measureTextHeight(textView, textView.getText().toString());
final int textHeight = measureTextHeight(textView, textView.getText(), maxLine);
if (textHeight < 0) {
// measure failed. setMaxLines directly.
textView.setMaxLines(maxLine);
return null;
}
final int minLines = textView.getMinLines();
final int targetHeight = textHeight + textView.getCompoundPaddingBottom() + textView.getCompoundPaddingTop();
return animatorToHeight(textView, targetHeight, new AnimatorListenerAdapter() {
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
}
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
textView.setMinLines(minLines);
textView.setMaxLines(maxLine);
}
});
}
@Nullable
public static ValueAnimator animatorToHeight(@NotNull final TextView textView, int h, @Nullable Animator.AnimatorListener listener) {
final int height = textView.getHeight();
if (height == h) {
return null;
}
ValueAnimator valueAnimator = new ValueAnimator();
valueAnimator.setIntValues(height, h);
long duration = makeDuration(h, height);
valueAnimator.setDuration(duration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (int) animation.getAnimatedValue();
textView.setHeight(value);
}
});
if (listener != null) {
valueAnimator.addListener(listener);
}
valueAnimator.start();
return valueAnimator;
}
private static long makeDuration(int h, int height) {
long d = (long) (DURATION * (Math.abs(h - height) * 1f / BASE_HEIGHT));
return Math.max(MIN_DURATION, Math.min(d, MAX_DURATION));
}
public static int measureTextHeight(@NotNull TextView textView, @NotNull CharSequence text) {
return measureTextHeight(textView, text, Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ? textView.getMaxLines() : Integer.MAX_VALUE);
}
public static int measureTextHeight(@NotNull TextView textView, @NotNull CharSequence text, int maxLines) {
if (sTempTextPaint == null) {
sTempTextPaint = new TextPaint();
}
sTempTextPaint.set(textView.getPaint());
sTempTextPaint.setTextSize(textView.getTextSize());
final int targetHeight = measureTextHeight(textView, text, sTempTextPaint, maxLines);
sTempTextPaint.reset();
return targetHeight;
}
public static int measureTextHeight(@NotNull TextView textView, @NotNull CharSequence text, @NotNull TextPaint textPaint, int maxLines) {
final boolean horizontallyScrolling = invokeAndReturnWithDefault(textView, "getHorizontallyScrolling", false);
final int availableWidth = horizontallyScrolling
? VERY_WIDE
: textView.getMeasuredWidth() - textView.getTotalPaddingLeft()
- textView.getTotalPaddingRight();
final int availableHeight = textView.getHeight() - textView.getCompoundPaddingBottom()
- textView.getCompoundPaddingTop();
if (availableWidth <= 0 || availableHeight <= 0) {
return -1;
}
TEMP_RECT_F.setEmpty();
TEMP_RECT_F.right = availableWidth;
// TEMP_RECT_F.bottom = availableHeight;
TEMP_RECT_F.bottom = VERY_WIDE;
// Needs reflection call due to being private.
Layout.Alignment alignment = invokeAndReturnWithDefault(
textView, "getLayoutAlignment", Layout.Alignment.ALIGN_NORMAL);
final StaticLayout layout = createStaticLayoutForMeasuringCompat(text, alignment, Math.round(TEMP_RECT_F.right), Integer.MAX_VALUE, textPaint, textView);
return layout.getLineTop(Math.min(layout.getLineCount(), maxLines));
}
private static StaticLayout createStaticLayoutForMeasuringCompat(CharSequence text, Layout.Alignment alignment, int availableWidth, int maxLines, TextPaint textPaint, TextView textView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return createStaticLayoutForMeasuring(text, alignment, availableWidth, maxLines, textPaint, textView);
} else {
return createStaticLayoutForMeasuringPre23(text, alignment, availableWidth, textPaint, textView);
}
}
@RequiresApi(Build.VERSION_CODES.M)
private static StaticLayout createStaticLayoutForMeasuring(CharSequence text, Layout.Alignment alignment, int availableWidth, int maxLines, TextPaint textPaint, TextView textView) {
// Can use the StaticLayout.Builder (along with TextView params added in or after
// API 23) to construct the layout.
final TextDirectionHeuristic textDirectionHeuristic = invokeAndReturnWithDefault(textView, "getTextDirectionHeuristic", TextDirectionHeuristics.FIRSTSTRONG_LTR);
final StaticLayout.Builder layoutBuilder = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, availableWidth);
return layoutBuilder.setAlignment(alignment)
.setLineSpacing(textView.getLineSpacingExtra(), textView.getLineSpacingMultiplier())
.setIncludePad(textView.getIncludeFontPadding())
.setBreakStrategy(textView.getBreakStrategy())
.setHyphenationFrequency(textView.getHyphenationFrequency())
.setMaxLines(maxLines == -1 ? Integer.MAX_VALUE : maxLines)
.setTextDirection(textDirectionHeuristic)
.build();
}
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static StaticLayout createStaticLayoutForMeasuringPre23(CharSequence text, Layout.Alignment alignment, int availableWidth, TextPaint textPaint, TextView textView) {
// Setup defaults.
float lineSpacingMultiplier = 1.0f;
float lineSpacingAdd = 0.0f;
boolean includePad = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Call public methods.
lineSpacingMultiplier = textView.getLineSpacingMultiplier();
lineSpacingAdd = textView.getLineSpacingExtra();
includePad = textView.getIncludeFontPadding();
} else {
// Call private methods and make sure to provide fallback defaults in case something
// goes wrong. The default values have been inlined with the StaticLayout defaults.
lineSpacingMultiplier = invokeAndReturnWithDefault(textView,
"getLineSpacingMultiplier", lineSpacingMultiplier);
lineSpacingAdd = invokeAndReturnWithDefault(textView,
"getLineSpacingExtra", lineSpacingAdd);
//noinspection ConstantConditions
includePad = invokeAndReturnWithDefault(textView,
"getIncludeFontPadding", includePad);
}
// The layout could not be constructed using the builder so fall back to the
// most broad constructor.
return new StaticLayout(text, textPaint, availableWidth,
alignment,
lineSpacingMultiplier,
lineSpacingAdd,
includePad);
}
private static <T> T invokeAndReturnWithDefault(@NonNull Object object, @NonNull final String methodName, @NonNull final T defaultValue) {
T result = null;
boolean exceptionThrown = false;
try {
// Cache lookup.
Method method = getTextViewMethod(methodName);
if (method != null) {
//noinspection unchecked
result = (T) method.invoke(object);
}
} catch (Exception ex) {
exceptionThrown = true;
Log.w(TAG, "Failed to invoke TextView#" + methodName + "() method", ex);
} finally {
if (result == null && exceptionThrown) {
result = defaultValue;
}
}
return result;
}
@SuppressLint("PrivateApi")
@Nullable
private static Method getTextViewMethod(@NonNull final String methodName) {
try {
Method method = sTextViewMethodByNameCache.get(methodName);
if (method == null) {
method = TextView.class.getDeclaredMethod(methodName);
if (method != null) {
method.setAccessible(true);
// Cache update.
sTextViewMethodByNameCache.put(methodName, method);
}
}
return method;
} catch (Exception ex) {
Log.w(TAG, "Failed to retrieve TextView#" + methodName + "() method", ex);
return null;
}
}
}