Tutorials Android How to Display HTML in Android TextView

How to Display HTML in Android TextView

In this tutorial, we will take a look into displaying HTML text in Android TextView.

Many times while you design an application, you may encounter a place where you will like to use HTML content in your screen. This may be to display a static “eula” or “help” content. In android there is a lovely class android.text.HTML that processes HTML strings into displayable styled text. Currently android doesn’t support all HTML tags.

Android API documentation does not stipulate what HTML tags are supported. Currently android seems support the following HTML tags to be rendered on TextView.

[box style=”4″]

<a href=”…”> <b>,  <big>, <blockquote>, <br>, <cite>, <dfn>
<div align=”…”>,  <em>, <font size=”…” color=”…” face=”…”>
<h1>,  <h2>, <h3>, <h4>,  <h5>, <h6>
<i>,  <img src=”…”>,  <p>, <small>
<strike>,  <strong>, <sub>, <sup>, <tt>, <u>[/box]

From HTML method returns displayable styled text from the provided HTML string. As per android’s official Documentations any tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.

Html.formHtml method takes an Html.TagHandler and an Html.ImageGetter as arguments as well as the text to parse. We can parse null as for the Html.TagHandler but you’d need to implement your own Html.ImageGetter as there isn’t a default implementation. The Html.ImageGetter needs to run synchronously and if you’re downloading images from the web you’ll probably want to do that asynchronously. But in my example I am using the images from resources to make my ImageGetter implementation simpler.

Display HTML in Android TextView

Create a new file inside layout folder and name it as main_layout.xml and paste the following code.

main_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your HTML text Below"/>

    <TextView
        android:id="@+id/html_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

Here is our Activity code, where we will render HTML tags in TextView.

MainActivity.java

package com.javatechig.example.ui;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

private final String htmlText = "<body><h1>Heading Text</h1><p>This tutorial " +
            "explains how to display " +
            "<strong>HTML </strong>text in android text view.&nbsp;</p>" +
            "<img src=\"hughjackman.jpg\">" +
            "<blockquote>Example from <a href=\"www.stacktips.com\">" +
            "stacktips.com<a></blockquote></body>";

@Override
protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);

          TextView htmlTextView = (TextView)findViewById(R.id.html_text);
          htmlTextView.setText(Html.fromHtml(htmlText, new ImageGetter(), null));

}

private class ImageGetter implements Html.ImageGetter {

public Drawable getDrawable(String source) {
        int id;
        if (source.equals("hughjackman.jpg")) {
               id = R.drawable.hughjackman;
        }
        else {
            return null;
        }

       Drawable d = getResources().getDrawable(id);
       d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
       return d;
     }
};

}

Here is the output of the above code

HTML in Android TextView

Total
0
Shares
guest
26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
simon
simon
9 years ago

“Currently android doesn’t support all HTML tags.”
I tend to disagree with this statement. The WebView widget does

user
user
9 years ago
Reply to  simon

@simon, I agree with you. I have depicted the same in my post. The support of HTML tags are limited to few tags as of now.
However it is nice to have feature in android, though developers can’t rely on it.

JavaTechig
JavaTechig
7 years ago
Reply to  simon

WebView is a replacement to browser, it is obvious to support all tags. However, when it comes to TextView rendering HTML tags, it is limited.

simon
simon
9 years ago

(sorry for the double post somehow i clicked post before finishing writing)

the WebView widget does support all HTML you can throw at it. android.text.HTML is really here only to put HTML in a simple TextView without a heavy interpretation.

It is true, however, that the extent of the supported tags should be documented officially somewhere.

user
user
9 years ago
Reply to  simon

@Simon, There is no official documentation available on the HTML tags support for android using Html.fromHtml.

However, You can see the supported tags information from official documentation. http://developer.android.com/reference/android/text/Html.html

pożyczki
pożyczki
9 years ago

This post is amazing. I realy love it!

Mojtaba Motamed
Mojtaba Motamed
8 years ago

hi.
can you help me about how to load image from web like(“”)
can we set asynktask in getDrwable function?
thanks

Nilanchala Panigrahy
Nilanchala Panigrahy
8 years ago

Yes. You can do it by using Html.ImageGetter

private class MyImageGetter implements Html.ImageGetter {

public Drawable getDrawable(String source) {
int id;

if (source.equals("test1.jpg")) {
id = R.drawable.test1;
}
else if (source.equals("test2.jpg")) {
id = R.drawable.test2;
}
else {
return null;
}

Drawable d = getResources().getDrawable(id);
d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
};

In the above code, it is using image from drawable. Alternatively you can write the logic to download the drawable from web.

String myHtml = "This will display an image to the right ";
mTextview.setText(Html.fromHtml(myHtml, new MyImageGetter(), null);

Mojtaba Motamed
Mojtaba Motamed
8 years ago

but you load image from drwable

i want to load image in html like this

This is text and this is an image <img src="http://downloadkade.com/images/uploads/Apple%20Safari%204%20beta.jpg&quot;

thanks

mustafa shaikh
mustafa shaikh
3 years ago

did you solve this..??

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

you have to put your layout inside scroll view.

Android ScrollView Example

thiago
thiago
7 years ago

hi,
can i get the HTML text from a separated file intead using a atributte and set it to a HTML file?
thanks

Versatile Vasu
Versatile Vasu
7 years ago

Hey @npanigrahy:disqus i have a website that has many functions apart from displaying text it is like a webpage that displays the functions like posting ,status and i want to add them in my app but not by using webview feature …
Any Suggestions??

JavaTechig
JavaTechig
7 years ago
Reply to  Versatile Vasu

Option-1, Use web view to display your website as is on your device.

Option-2, Your website should have the RSS or JSON feed in order to make it accessible from mobile app. In such case you can build pure native application.

Aritra
Aritra
7 years ago

getResources is a function of context class. So Activity, ActionbarActivity, FragmentActivity would have it. are u calling it from activity or a fragment or an other class?

but getDrawable is deprecated.(the strikeout means deprecated)

so u should use ContextCompat.getDrawable(this, R.drawable.your_drawable) for more info check this SO question

http://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22

Nilanchala Panigrahy
Nilanchala Panigrahy
6 years ago

For that you may requireHTML spanner library.

HTMLSpanner

Xavi (Drakgoku1)
Xavi (Drakgoku1)
6 years ago

Not works, I tried this solution.

eragon
eragon
6 years ago

I get an error for the line ” id = R.drawable.hughjackman;” stating hughjackman cannot be resolved to a type. How do I fix this?

Jayke R. Huempfner
Jayke R. Huempfner
6 years ago
Reply to  eragon

Do you have an image named “hughjackman” in your “Drawable” folder? If not, that’s where that issue comes from. Change “R.drawable.hughjackman” to a different image.

Nilanchala Panigrahy
Nilanchala Panigrahy
6 years ago

Not quite sure if the latest webkit supports. You need to give a try. But as far as I know, it doesn’t support.

Nilanchala Panigrahy
Nilanchala Panigrahy
6 years ago

Your ImageGetter should handle that.

sushant
sushant
6 years ago

how can fetch data from http://equityright.com/API/news.php this url

Arvind Subramanian
Arvind Subramanian
6 years ago

Is it possible to modify the styling of existing tags, as we do in browser by css?

SeePhoo
SeePhoo
6 years ago

Thanks a big lot, mate!

Sourav Roy
Sourav Roy
5 years ago

If an image link is supplied in and it’s not in drawable then how we can show the image? Talking about dynamic image

mustafa shaikh
mustafa shaikh
3 years ago

Can we show GIF with this format if possible how can it possible..???

Previous Post
Android Tutorials

Android Dialog Example

Next Post
Android Tutorials

How to Get Key Hashes for Android App Facebook Integration

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
26
0
Would love your thoughts, please comment.x
()
x