我有多行 TextView,我只需要格式化它的单行。由于字体大小和样式是动态的,我需要它自动格式化“第一行”。
此 TextView 显示一个没有换行的字符串,它会自动换行,我需要格式化第一个换行行。
请检查附图:
最佳答案
我找到了使用 StaticLayout 的解决方案。
private TextView tvTitle; //bold title with maxLines = 1
private TextView tvText; //the rest of the text
//initialize views, etc...
private void showText(@Nonnull String text) {
tvTitle.setText(text);
tvTitle.post(() -> {
String ellipsizedText = getEllipsizedText(text, tvTitle);
tvText.setText(ellipsizedText);
});
}
private static String getEllipsizedText(String text, TextView textView) {
StaticLayout staticLayout = getStaticLayout(text,
textView.getPaint(),
textView.getWidth(),
1,
null);
return text.substring(staticLayout.getLineEnd(0));
}
private static StaticLayout getStaticLayout(CharSequence text,
TextPaint paint,
int width,
int maxLines,
TextUtils.TruncateAt ellipsize) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return StaticLayout.Builder.obtain(text, 0, text.length(), paint, width)
.setTextDirection(TextDirectionHeuristics.FIRSTSTRONG_LTR)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setLineSpacing(0f, 1f)
.setIncludePad(false)
.setEllipsize(ellipsize)
.setEllipsizedWidth(width)
.setMaxLines(maxLines)
.build();
} else {
return new StaticLayout(text,
paint,
width,
Layout.Alignment.ALIGN_NORMAL,
1f,
0f,
false);
}
}
关于android - 在 Android 中格式化多行 TextView 的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961621/