Android,将文本从 Json 格式化为 HTML 删除新行和空格 [英] Android, format text from Json to HTML removes new lines and white spaces

查看:47
本文介绍了Android,将文本从 Json 格式化为 HTML 删除新行和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Json 接收的文本是这样的:

<块引用>

 这是句子 1.这是<b>句子2</b>.

我使用此代码格式化为 HTML 并将其传递给 textView:

private void textChecker(TextView view, String formattedText) {如果 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {view.setText(Html.fromHtml(formattedText, Html.FROM_HTML_MODE_LEGACY));} 别的 {view.setText(Html.fromHtml(formattedText));}}

问题是新文本会消除开头的任何空格或沿途的新行.输出如下所示:

<块引用>

这是句子 1.这是句子 2.

如何格式化文本以使用 HTML 标签并保持原始格式/对齐方式?

解决方案

目前看来唯一合理的解决方案是在 java 的 json 字符串中用 HTML 标签替换所需的字符:

jsonText.replace("\r\n", "
");

但如果你们中有人有更优雅/更简单的解决方案,请随时发布!

The text is received from a Json is like this:

  This is sentence 1.

  This is <b>sentence 2</b>.

And I use this code to format to HTML and pass it to a textView:

private void textChecker(TextView view, String formattedText) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        view.setText(Html.fromHtml(formattedText, Html.FROM_HTML_MODE_LEGACY));
    } else {
        view.setText(Html.fromHtml(formattedText));
    }
}

The problem is that the new text will dismiss any white spaces at the beginning or new lines along the way. And the output looks like this:

This is sentence 1. This is sentence 2.

How do I format the text to use the HTML tags and also keep the original formatting/alignment?

解决方案

The only solution that seems reasonable, for now, is to replace the required characters with HTML tags, in the json string in java:

jsonText.replace("\r\n", "<br/>");

But if any of you have a more elegant/simple solution, feel free to post it!

这篇关于Android,将文本从 Json 格式化为 HTML 删除新行和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆