我有简单的HTML:

<h2>Title</h2><br>
<p>description here</p>

我想在TextView中显示HTML样式的文本。如何做到这一点?


当前回答

您可以使用Github上的HtmlDsl库为Android TextView构建有效的HTML:https://github.com/jaredrummler/HtmlDsl.

该库只支持Android提供的元素和属性,提供语法糖,使代码更容易理解,更不容易出错。

创建一些HTML的示例:

textView.setHtml {
    h3("Android Versions:")
    ul {
        li {
            a(href = "https://developer.android.com/about/versions/12/get") {
                +"Android 12 Beta"
            }
        }
        li("Android 11")
        li("Android 10")
        li("Pie")
        li("Oreo")
        li("Nougat")
        li("Marshmallow")
        li("Lollipop")
        // ...
    }

    small {
        sub {
            +"by "
            a {
                href = "https://github.com/jaredrummler"
                text = "Jared Rummler"
            }
        }
    }
}

Android TextView支持的HTML元素:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<ul>
<li>

其他回答

每当您编写自定义文本视图时,基本的HTML设置文本功能将从某些设备上消失。

因此,我们需要执行以下附加步骤,使其有效

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}

我还想建议以下项目:https://github.com/NightWhistler/HtmlSpanner

用法与默认的android转换器几乎相同:

(new HtmlSpanner()).fromHtml()

在我已经开始自己实现html到可扩展转换器之后发现了它,因为标准html.fromHtml在渲染控制上没有足够的灵活性,甚至不可能使用ttf中的自定义字体

我已经使用web视图实现了这一点。在我的例子中,我必须从URL加载图像以及文本视图中的文本,这对我很有用。

WebView myWebView =new WebView(_context);
        String html = childText;
        String mime = "text/html";
        String encoding = "utf-8";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);

为strings.xml文件中的字符串使用CData部分以在TextView中实际显示html内容的最佳方法。下面的代码片段将为您提供大致思路。

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));

即使在使用string.format方法格式化文本之后,字符串文本中的CData部分也会保持html标记数据的完整性。因此,Html.fromHtml(str)工作正常,您将在欢迎消息中看到粗体文本。

输出:

欢迎来到您最喜爱的音乐应用商店。登录身份:username

您可以像这样使用简单的Kotlin扩展函数:

fun TextView.setHtmlText(source: String) {
    this.text = HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

和用法:

textViewMessage.setHtmlText("Message: <b>Hello World</b>")