背景
前段時(shí)間在寫一個(gè)TextView的屬性的時(shí)候,需要設(shè)置最大字?jǐn)?shù),然后超出部分省略號顯示。這個(gè)功能其實(shí)是非常簡單的,于是我不假思索的就寫下了這段功能。(下面用測試代碼代替)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是一段測試的文本"
android:maxEms="7"
android:ellipsize="end"
android:maxLines="1"
android:lineSpacingMultiplier="1.5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
稀疏平常的一段代碼,run一下看下效果:
有點(diǎn)奇怪了,文本并沒有在第七個(gè)字開始變成省略號。
一開始以為是我記錯(cuò)了屬性,把maxEms改成maxLength,但是似乎并沒有效果。Google了一下找到的都是TextView文本多行導(dǎo)致的ellipsize失效,但是我們這里使用的就是單行,不存在多行情況,所以問題變得特別奇怪了。
后來嘗試著將android:lineSpacingMultiplier屬性去掉以后,看了下效果:

發(fā)現(xiàn)竟然解決了問題!于是比較疑惑了,為啥行間距設(shè)置會影響ellipsize屬性。當(dāng)然稀里糊涂的解決問題并不是我的風(fēng)格,所以決定深入了解下為什么會產(chǎn)生這個(gè)問題。
當(dāng)然在了解這個(gè)問題之前,首先先來看下,TextView正常情況下是如何設(shè)置Ellipsize屬性的。
TextView在繪制的時(shí)候會借助Layout類,而Layout只是個(gè)抽象類,所以根據(jù)不同的情況,TextView會創(chuàng)建不同的Layout子類來賦值自己繪制文字。所以我們需要從onMeasure看起:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mLayout == null) {
makeNewLayout(want, hintWant, boring, hintBoring,
width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
}
}
onMeasure里面會先判斷Layout是否存在,不存在的時(shí)候執(zhí)行makeNewLayout創(chuàng)建對應(yīng)的Layout。
@VisibleForTesting
@UnsupportedAppUsage
public void makeNewLayout(int wantWidth, int hintWidth,
BoringLayout.Metrics boring,
BoringLayout.Metrics hintBoring,
int ellipsisWidth, boolean bringIntoView) {
mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
effectiveEllipsize, effectiveEllipsize == mEllipsize);
}
makeNewLayout接下來會調(diào)用makeSingleLayout方法。
/**
* @hide
*/
protected Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
boolean useSaved) {
Layout result = null;
...代碼省略...
if (result == null) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed,
0, mTransformed.length(), mTextPaint, wantWidth)
.setAlignment(alignment)
.setTextDirection(mTextDir)
.setLineSpacing(mSpacingAdd, mSpacingMult)
.setIncludePad(mIncludePad)
.setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing)
.setBreakStrategy(mBreakStrategy)
.setHyphenationFrequency(mHyphenationFrequency)
.setJustificationMode(mJustificationMode)
.setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
if (shouldEllipsize) {
builder.setEllipsize(effectiveEllipsize)
.setEllipsizedWidth(ellipsisWidth);
}
result = builder.build();
}
return result;
}
正常情況下,設(shè)置了maxEms的TextView會創(chuàng)建StaticLayout方法,然后設(shè)置對應(yīng)的Ellipsize屬性。接下來TextView會在onDraw的時(shí)候調(diào)用Layout的draw方法進(jìn)行繪制
public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
int cursorOffsetVertical) {
final long lineRange = getLineRangeForDraw(canvas);
int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
if (lastLine < 0) return;
drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
firstLine, lastLine);
drawText(canvas, firstLine, lastLine);
}
此處執(zhí)行drawText方法,下面直接給出調(diào)用鏈:
Layout#drawText()
TextLine#set()
TextUtils#getChars()
Ellipsizer#getChars()
Layout#ellipsize()
TextUtils#getEllipsisString()
最后通過調(diào)用textUtils的getEllipsisString方法獲取到省略號,然后拼接到字符串當(dāng)中去。
那么問題來了:為什么設(shè)置了lineSpacingMultiplier以后Ellipsize就失效了呢。這就要在onMeasure里面找原因了
if (mMaxWidthMode == EMS) {
width = Math.min(width, mMaxWidth * getLineHeight());
} else {
width = Math.min(width, mMaxWidth);
}
onMeasure方法里面有上面這段代碼,當(dāng)設(shè)置了maxEms的時(shí)候,width也就是控件的寬度就是去當(dāng)前width和mMaxWidth * getLineHeight()的最小值,width就是當(dāng)前測量的android:text所包含的文案的總寬度,而mMaxWidth就是maxEms屬性值即7。那么再來看下getLineHeight獲取的是什么?
public int getLineHeight() {
return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd);
}
getLineHeight其實(shí)獲取的就是行高,mSpacingMult就是lineSpacingMultiplier的屬性,mSpacingAdd則是lineSpacingExtra屬性,總的來說就是設(shè)置最后的行高。
那么width和mMaxWidth * getLineHeight就目前來看是誰大呢,我們不妨算一下:
width=當(dāng)前文字總數(shù)即 9 * 文字本身寬度
mMaxWidth * getLineHeight() = 7 * 文字本身寬度 * 1.5
很明顯width更小,所以最后設(shè)置的width就是當(dāng)前文字總數(shù)即 9 * 文字本身寬度了。
width什么作用呢?在獲取到width以后,接下來就是makeNewLayout方法了,然后會在makeSingleLayout里面創(chuàng)建對應(yīng)的Layout實(shí)例。
protected Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
boolean useSaved) {
Layout result = null;
if (useDynamicLayout()) {
...代碼省略
} else {
if (boring == UNKNOWN_BORING) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
if (boring != null) {
mBoring = boring;
}
}
if (boring != null) {
if (boring.width <= wantWidth
&& (effectiveEllipsize == null || boring.width <= ellipsisWidth)) {
if (useSaved && mSavedLayout != null) {
result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
wantWidth, alignment, mSpacingMult, mSpacingAdd,
boring, mIncludePad);
} else {
result = BoringLayout.make(mTransformed, mTextPaint,
wantWidth, alignment, mSpacingMult, mSpacingAdd,
boring, mIncludePad);
}
if (useSaved) {
mSavedLayout = (BoringLayout) result;
}
} else if (shouldEllipsize && boring.width <= wantWidth) {
if (useSaved && mSavedLayout != null) {
result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
wantWidth, alignment, mSpacingMult, mSpacingAdd,
boring, mIncludePad, effectiveEllipsize,
ellipsisWidth);
} else {
result = BoringLayout.make(mTransformed, mTextPaint,
wantWidth, alignment, mSpacingMult, mSpacingAdd,
boring, mIncludePad, effectiveEllipsize,
ellipsisWidth);
}
}
}
}
if (result == null) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed,
0, mTransformed.length(), mTextPaint, wantWidth)
.setAlignment(alignment)
.setTextDirection(mTextDir)
.setLineSpacing(mSpacingAdd, mSpacingMult)
.setIncludePad(mIncludePad)
.setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing)
.setBreakStrategy(mBreakStrategy)
.setHyphenationFrequency(mHyphenationFrequency)
.setJustificationMode(mJustificationMode)
.setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
if (shouldEllipsize) {
builder.setEllipsize(effectiveEllipsize)
.setEllipsizedWidth(ellipsisWidth);
}
result = builder.build();
}
return result;
}
我們可以看到只有在result為空的情況下才會創(chuàng)建StaticLayout,而我們此時(shí)傳入的wantWidth就是當(dāng)前文字總數(shù)的寬度,boring.width獲取到也是當(dāng)前文字總數(shù)的寬度。所以最后會創(chuàng)建BoringLayout。
而BoringLayout重寫了Layout的draw方法,也就是說當(dāng)TextView在調(diào)用mLayout.draw的時(shí)候最后其實(shí)進(jìn)到BoringLayout的draw方法中:
@Override
public void draw(Canvas c, Path highlight, Paint highlightpaint,
int cursorOffset) {
if (mDirect != null && highlight == null) {
c.drawText(mDirect, 0, mBottom - mDesc, mPaint);
} else {
super.draw(c, highlight, highlightpaint, cursorOffset);
}
}
BoringLayout的draw方法很簡單的就是調(diào)用了canvas的drawText,所以Ellipsize就會失效了。
總結(jié)
如果需求需要設(shè)置lineSpacingMultiplier或者是lineSpacingExtra,那么似乎并沒有什么特別好的解決方案可以防止Ellipsize失效。
PS:其實(shí)Ellipsize并不是真正的失效,而是此時(shí)最小寬度與boring的width一致了。如果想要實(shí)現(xiàn)Ellipsize為End的效果那么可以設(shè)置maxEms為5(以上面給出的demo為例)
另外就是對于width的獲取操作比較費(fèi)解,不懂為啥在獲取寬度的時(shí)候要用行高作為乘數(shù)。