android - 在 Android 中格式化多行 TextView 的第一行

标签 android textview format render

我有多行 TextView,我只需要格式化它的单行。由于字体大小和样式是动态的,我需要它自动格式化“第一行”。

此 TextView 显示一个没有换行的字符串,它会自动换行,我需要格式化第一个换行行。

请检查附图:

enter image description here

最佳答案

我找到了使用 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/

相关文章:

format - 如何在 tcl 中以表格格式打印?

android - 无法检测到在 Android 中何时接听了拨出电话

android在textview中制作上标文本被削减

html - 在 C# 中导出 HTML 表格时设置 word 文档的边距和属性

android - 在android底部设置textview

mysql - 如何在android中的 TextView 中发布MySQL数据

python : How to format large number without comma

java - 如何移动操作栏中的标题选项卡指示器?

android - Firebase 动态链接 PendingDynamicLinkData 返回 null android

android - 在运行时更改区域设置不影响 fragment