我有以下方法,可以放大TextView
中的第一个字符。
private void makeFirstLetterBig(TextView textView, String title) {
final SpannableString spannableString = new SpannableString(title);
int position = 0;
spannableString.setSpan(new RelativeSizeSpan(2.0f), position, position + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//textView.setText(spannableString.toString());
textView.setText(spannableString, BufferType.SPANNABLE);
}
这是正在使用的
TextView
。<TextView
android:id="@+id/title_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="?attr/newsTitleTextViewSelector"
android:duplicateParentState="true"
android:text="TextView" />
下面是棉花糖6号之前的结果。
看起来很不错,因为当文本内容换行到第二行时,第一个大字符不会影响第二行。
然而,当在棉花糖6中运行相同的应用程序时,我得到以下结果。
似乎,大字符“i”正在为整个文本内容创建一个大填充。这导致第二行(与amazon)与第一行有很大的行距。
我能知道吗,在棉花糖6里我怎么能避免这样的问题呢?我希望得到和棉花糖前一样的结果。
p/s我也在https://code.google.com/p/android/issues/detail?id=191187提交了一份报告。
更新
2015年12月9日,谷歌已经修复了这个问题,并将在android 6.0.1-https://code.google.com/p/android/issues/detail?id=191187中发布。
最佳答案
问题是由generate
的StaticLayout
方法中的错误引起的。
这个bug与我最初的想法有点不同,它不会影响所有行,而只影响放大字符之后的行,如您从屏幕截图中看到的:
在棉花糖中添加了FontMetrics
缓存以避免重新计算,如source code中的注释所述:
// measurement has to be done before performing line breaking
// but we don't want to recompute fontmetrics or span ranges the
// second time, so we cache those and then use those stored values
不幸的是,缓存中可用的
fm.descent
值如果低于上一个缓存值,则会被丢弃,如snippet中所示:for (int spanStart = paraStart, spanEnd; spanStart < paraEnd; spanStart = spanEnd) {
// retrieve end of span
spanEnd = spanEndCache[spanEndCacheIndex++];
// retrieve cached metrics, order matches above
fm.top = fmCache[fmCacheIndex * 4 + 0];
fm.bottom = fmCache[fmCacheIndex * 4 + 1];
fm.ascent = fmCache[fmCacheIndex * 4 + 2];
fm.descent = fmCache[fmCacheIndex * 4 + 3];
fmCacheIndex++;
if (fm.top < fmTop) {
fmTop = fm.top;
}
if (fm.ascent < fmAscent) {
fmAscent = fm.ascent;
}
if (fm.descent > fmDescent) {
fmDescent = fm.descent;
}
if (fm.bottom > fmBottom) {
fmBottom = fm.bottom;
}
....
一旦该值达到最大值,它将永远不会减少,这就是为什么每个后续行都有一个增加的行空间。