How to display HTML in TextView?

I have simple HTML:

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

I want to display HTML styled text it in TextView. How to do this?


Asked by: Kimberly549 | Posted: 24-01-2022






Answer 1

You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.

This is what you should do in Java

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>"));
}

And in Kotlin:

textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(html)
}

Answered by: Emily99 | Posted: 25-02-2022



Answer 2

setText(Html.fromHtml(bodyData)) is deprecated after api 24. Now you have to do this:

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

Answered by: Rebecca535 | Posted: 25-02-2022



Answer 3

Have a look on this: https://stackoverflow.com/a/8558249/450148

It is pretty good too!!

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

It works only for few tags.

Answered by: Alford636 | Posted: 25-02-2022



Answer 4

If you want to be able to configure it through xml without any modification in java code you may find this idea helpful. Simply you call init from constructor and set the text as 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"/>

Answered by: Dainton881 | Posted: 25-02-2022



Answer 5

If you are trying to show HTML from a string resource id, the formatting may not show up on screen. If that is happening to you, try using CDATA tags instead:

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

See this post for further details.

Answered by: Lenny565 | Posted: 25-02-2022



Answer 6

The below code gave best result for me.

TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);

Answered by: Brooke669 | Posted: 25-02-2022



Answer 7

I know this question is old. Other answers here suggesting Html.fromHtml() method. I suggest you to use HtmlCompat.fromHtml() from androidx.core.text.HtmlCompat package. As this is backward compatible version of Html class.

Sample code:

import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;

String htmlString = "<h1>Hello World!</h1>";

Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);

TextView tvOutput = (TextView) findViewById(R.id.text_view_id);

tvOutput.setText(spanned);

By this way you can avoid Android API version check and it's easy to use (single line solution).

Answered by: Anna805 | Posted: 25-02-2022



Answer 8

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

Answered by: Emma683 | Posted: 25-02-2022



Answer 9

If you just want to display some html text and don't really need a TextView, then take a WebView and use it like following:

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

This does not restrict you to a few html tags either.

Answered by: Brooke417 | Posted: 25-02-2022



Answer 10

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

Answered by: Anna686 | Posted: 25-02-2022



Answer 11

It's worth mentioning that the method Html.fromHtml(String source) is deprecated as of API level 24. If that's your target API, you should use Html.fromHtml(String source, int flags) instead.

Answered by: Ada364 | Posted: 25-02-2022



Answer 12

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)
}

Answered by: Oliver137 | Posted: 25-02-2022



Answer 13

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

Answered by: Luke266 | Posted: 25-02-2022



Answer 14

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.

Answered by: John585 | Posted: 25-02-2022



Answer 15

It has been suggested through various answers to use the Html framework class as suggested here, but unfortunately this class has different behavior in different versions of Android and various unaddressed bugs, as demonstrated in issues 214637, 14778, 235128 and 75953.

You may therefore want to use a compatibility library to standardize and backport the Html class across Android versions which includes more callbacks for elements and styling:

Github project HtmlCompat

While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:

Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
//        imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);

Answered by: Aida184 | Posted: 25-02-2022



Answer 16

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 to use HtmlCompat.fromHtml than Html.fromHtml as there is less code- only one line of code, and it's recommended way to use it.

Answered by: Aida803 | Posted: 25-02-2022



Answer 17

simply use enter image description here

checkBoxTextView.text =
        Html.fromHtml("<p><font color=#666666>I agree to</font><font color=#0173B7>  <b><u>Terms & Conditions</u></b></font><font color=#666666> and the <u></font><b><font color=#0173B7>Privacy Policy</font></u></b></font></p>")

Answered by: William341 | Posted: 25-02-2022



Answer 18

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

Answered by: Adelaide172 | Posted: 25-02-2022



Answer 19

String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)

Answered by: Lana902 | Posted: 25-02-2022



Answer 20

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

Answered by: Alina360 | Posted: 25-02-2022



Answer 21

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()));
    }
}

Answered by: Nicole127 | Posted: 25-02-2022



Answer 22

Simply use:

String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));

Answered by: Samantha566 | Posted: 25-02-2022



Answer 23

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

Answered by: Sawyer835 | Posted: 25-02-2022



Answer 24

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;
}

Answered by: Oliver536 | Posted: 25-02-2022



Answer 25

People have suggested subclass for TextView, WebView and all sorts of solutions. I wonder why nobody mentioned a simple binding adapter.

@BindingAdapter(value = ["htmlText"])
fun TextView.setHtmlText(string: String?) {
    text = HtmlCompat.fromHtml(string?:"", HtmlCompat.FROM_HTML_MODE_COMPACT)
}

So your TextView xml will look like

<TextView
   ...
   htmlText="<p>Your <b>HTML</b> text</p>"
   ... />

Answered by: Audrey257 | Posted: 25-02-2022



Answer 26

May I suggest a somewhat hacky but still genius solution! I got the idea from this article and adapted it for Android. Basically you use a WebView and insert the HTML you want to show and edit in an editable div tag. This way when the user taps the WebView the keyboard appears and allows editing. They you just add some JavaScript to get back the edited HTML and voila!

Here is the code:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

And here is the component as a Gist.

Note: I didn't need the height change callback from the original solution so that's missing here but you can easily add it if needed.

Answered by: Tess768 | Posted: 25-02-2022



Answer 27

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>")

Answered by: Stella491 | Posted: 25-02-2022



Answer 28

You can build valid HTML for Android TextView using the HtmlDsl library on Github: https://github.com/jaredrummler/HtmlDsl.

The library provides syntactic sugar to make the code more understandable and less error-prone by only supporting elements and attributes that are rendered by Android.

Example creating some 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"
            }
        }
    }
}

Supported HTML elements for Android TextView:

<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>

Answered by: Sienna281 | Posted: 25-02-2022



Similar questions

android - Can I hook when user copy or paste on TextView?

When user copy or paste on TextView, Is there anyone explains me what happen on TextView. If some methods called while user click 'Copy' or 'Paste' in menus, I'd like to hook them and replace them with my own one. Here is what I want to do. 1. user copy or paste some string to my TextView. 2. some string copied and paste on my Textview. 3. Before some string is added on Textview, I want to check or change string.


android - How to bind more then one column to a textview

I am curious if there is a way to bind more then one db column to a resource. I need to bind more information to R.id.secondLine then just the difficulty column. But I'm unsure how to go about this? I'm currently subclassing SimpleCursorAdapter. Should I subclass another adapter? If so How to do I go about it? Cursor activityHikes = mDbAdapter.fetchAllHikes(false); startManagingCursor(activityHikes)...


Android TextView Text not getting wrapped

Can anyone tell me what's going wrong with the text? Text longer than one line doesn't wrap to the next line but goes beyond the screen. Following is the code: &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="4dip"&gt; &lt;LinearL...


how to change text in Android TextView

I tried to do this @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); t=new TextView(this); t=(TextView)findViewById(R.id.TextView01); t.setText("Step One: blast egg"); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printSta...


android - Color of the text in TextView changes color

In android, when I press on a TextView, the text changes color (from white to grey). Can you please tell me how can I disable that functionality? Thank you.


android - Can I hook when user copy or paste on TextView?

When user copy or paste on TextView, Is there anyone explains me what happen on TextView. If some methods called while user click 'Copy' or 'Paste' in menus, I'd like to hook them and replace them with my own one. Here is what I want to do. 1. user copy or paste some string to my TextView. 2. some string copied and paste on my Textview. 3. Before some string is added on Textview, I want to check or change string.


Maximum line length on Android TextView

I'm putting a formatted single line text (no \n's) to a noneditable TextView. In the navigation of the program, the text can be changed. On some text, the TextView shrinks to 0x0 pixel and I can see nothing! I added some menus to truncate the text 10 characters each time and I found that if the number of characters are larger than 4470, the TextView shrinks. Splitting the text into several lines by putting \n in be...


android - How to bind more then one column to a textview

I am curious if there is a way to bind more then one db column to a resource. I need to bind more information to R.id.secondLine then just the difficulty column. But I'm unsure how to go about this? I'm currently subclassing SimpleCursorAdapter. Should I subclass another adapter? If so How to do I go about it? Cursor activityHikes = mDbAdapter.fetchAllHikes(false); startManagingCursor(activityHikes)...


Android TextView Text not getting wrapped

Can anyone tell me what's going wrong with the text? Text longer than one line doesn't wrap to the next line but goes beyond the screen. Following is the code: &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="4dip"&gt; &lt;LinearL...


Ordered lists inside an Android TextView

I want to display an ordered list inside a TextView, for example: 1) item 1 2) item 2 Using the following layout: &lt;TextView android:text="&lt;ol&gt;&lt;li&gt;item 1\n&lt;/li&gt;&lt;li&gt;item 2\n&lt;/li&gt;&lt;/ol&gt; /&gt; I get: item 1 item 2 How can I change the bullets to numbers? Thanks.


how to change text in Android TextView

I tried to do this @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); t=new TextView(this); t=(TextView)findViewById(R.id.TextView01); t.setText("Step One: blast egg"); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printSta...


android - Color of the text in TextView changes color

In android, when I press on a TextView, the text changes color (from white to grey). Can you please tell me how can I disable that functionality? Thank you.


How can you display upside down text with a textview in Android?

How can you display upside down text with a textview in Android? In my case I have a 2 player game, where they play across from each other. I want to display test to the second player oriented to them. This was the solution I implemented after AaronMs advice The class that does the overriding, bab.foo.UpsideDownText package bab.foo; import android.content.Context; import andr...


textview - How to know all id's that i have in the file main.xml in android?

i'm new at Android world, and i have a doubt, is there any method that give me the name of the id's i create in main.xml? For example i have this: main.xml &lt;TextView android:id="@+id/text1" android:layout_width="70px" android:layout_height="70px" android:text="Google" /&gt; &lt;TextView android:id="@+id/text2" android:layout_width="70px" android:layout_h...


How do I add a newline to a TextView in Android?

When I define a TextView in xml, how do I add a new line to it? \n seems not to work. &lt;TextView android:id=&quot;@+id/txtTitlevalue&quot; android:text=&quot;Line1 -\nLine2&quot; android:layout_width=&quot;54dip&quot; android:layout_height=&quot;fill_parent&quot; android:textSize=&quot;11px&quot; /&gt;






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top