我有简单的HTML:

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

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


当前回答

简单使用Html.fromHtml(“Html字符串”)。这会奏效的。如果字符串具有类似<h1>的标记,则空格将出现。但我们无法消除这些空间。如果仍要删除空格,则可以删除字符串中的标记,然后将字符串传递给Html.fromHtml(“Html string”);方法。通常,这些字符串也来自服务器(动态),但如果将字符串原样传递给方法比从字符串中删除标记更好,则不经常这样做。

其他回答

看看这个:https://stackoverflow.com/a/8558249/450148

它也很好!!

<resource>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

它只适用于少数标签。

如果您希望能够通过xml配置它,而不需要对java代码进行任何修改,您可能会发现这个想法很有用。只需从构造函数调用init并将文本设置为html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml格式:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>

值得一提的是,从API级别24开始,Html.fromHtml(字符串源代码)方法已被弃用。如果这是你的目标API,你应该使用Html.fromHtml(字符串源,int标志)。

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

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

public class CustomTextView extends TextView {

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

我已经使用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);