如何在TextView中显示HTML?

我有简单的HTML

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

我想在中显示HTML样式的文本TextView这该怎么做?

逆天猪猪2020/03/17 16:19:42

If you use androidx.* classes in your project, you should use HtmlCompat.fromHtml(text, flag). Source of the method is:

@NonNull public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) { if (Build.VERSION.SDK_INT >= 24) { return Html.fromHtml(source, flags); } //noinspection deprecation return Html.fromHtml(source); }

It is better way than Html.fromHtml as there is less code, only one line, and recommended way to use it.

伽罗古一2020/03/17 16:19:42

Simply use:

String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));
Stafan阳光2020/03/17 16:19:42

You can use simple Kotlin extension function like this:

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

And usage:

textViewMessage.setHtmlText("Message: <b>Hello World</b>")
JinJinPro2020/03/17 16:19:42

Use below code to get the solution:

textView.setText(fromHtml("<Your Html Text>"))

Utitilty Method

public static Spanned fromHtml(String text)
{
    Spanned result;
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(text);
    }
    return result;
}
阳光逆天2020/03/17 16:19:42

Created Kotlin extensions to convert html from String -

fun String?.toHtml(): Spanned? {
    if (this.isNullOrEmpty()) return null
    return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_COMPACT)
}
神奇神乐GO2020/03/17 16:19:41
public class HtmlTextView extends AppCompatTextView {

public HtmlTextView(Context context) {
    super(context);
    init();
}

private void init(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
    } else {
        setText(Html.fromHtml(getText().toString()));
    }
 }
}

update of answer above

阿飞A飞云2020/03/17 16:19:41

I have implemented this using web view. In my case i have to load image from URL along with the text in text view and this works for me.

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);
番长卡卡西2020/03/17 16:19:41

Whenever you write custom text view basic HTML set text feature will be get vanished form some of the devices.

So we need to do following addtional steps make is work

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}
AL村村2020/03/17 16:19:41

Make a global method like:

public static Spanned stripHtml(String html) {
            if (!TextUtils.isEmpty(html)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
                } else {
                    return Html.fromHtml(html);
                }
            }
            return null;
        }

You can also use it in your Activity/Fragment like:

text_view.setText(stripHtml(htmlText));
GO神乐2020/03/17 16:19:40
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
神无逆天2020/03/17 16:19:40

如果您只想显示一些html文本,而实际上并不需要a TextView,请WebView使用a 并按如下所示使用它:

String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);

这也不限制您使用几个html标签。

村村达蒙LEY2020/03/17 16:19:40

Simple use Html.fromHtml("html string"). This will work. If the string has tags like <h1> then spaces will come. But we cannot eliminate those spaces. If you still want to remove the spaces, then you can remove the tags in the string and then pass the string to the method Html.fromHtml("html string"); . Also generally these strings come from server(dynamic) but not often, if it is the case better to pass the string as it is to the method than try to remove the tags from the string.

西里小胖小卤蛋2020/03/17 16:19:40

I would like also to suggest following project: https://github.com/NightWhistler/HtmlSpanner

Usage is almost the same as default android converter:

(new HtmlSpanner()).fromHtml()

Found it after I already started by own implementation of html to spannable converter, because standard Html.fromHtml does not provide enough flexibility over rendering control and even no possibility to use custom fonts from ttf

西门Harry梅2020/03/17 16:19:40

The best approach to use CData sections for the string in strings.xml file to get a actual display of the html content to the TextView the below code snippet will give you the fair idea.

//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));

CData section in string text keeps the html tag data intact even after formatting text using String.format method. So, Html.fromHtml(str) works fine and you’ll see the bold text in Welcome message.

Output:

Welcome, to your favorite music app store. Logged in as: username

AGO2020/03/17 16:19:39
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
    SiteLink= (TextView) findViewById(R.id.textViewSite);
    SiteLink.setText(Html.fromHtml(value));
    SiteLink.setMovementMethod(LinkMovementMethod.getInstance());
Eva神无2020/03/17 16:19:39

如果您尝试从字符串资源ID显示HTML,则格式可能不会显示在屏幕上。如果发生这种情况,请尝试使用CDATA标记代替:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

有关更多详细信息,请参见此帖子

小宇宙樱2020/03/17 16:19:39

下面的代码对我来说是最好的结果。

TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);
Pro蛋蛋2020/03/17 16:19:39

如果您希望能够通过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"/>
村村Mandy2020/03/17 16:19:39

的setText(Html.fromHtml(bodyData))弃用 API 24后,现在你必须这样做:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
      tvDocument.setText(Html.fromHtml(bodyData,Html.FROM_HTML_MODE_LEGACY));
 } else {
      tvDocument.setText(Html.fromHtml(bodyData));
 }
L十三2020/03/17 16:19:39

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

太好了!!

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

它仅适用于少量标签。

西门LEY2020/03/17 16:19:38

您需要使用Html.fromHtml()XML字符串中的HTML。仅在布局XML中引用带有HTML的字符串将不起作用。

这是您应该做的:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else { 
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}