TextView to display simple HTML

Overview

Project stopped

This project has been stopped. 4.0 is the last release.

Feel free to fork this project and take over maintaining.

HtmlTextView for Android

HtmlTextView is an extended TextView component for Android, which can load very simple HTML by converting it into Android Spannables for viewing.

In addition to a small set of HTML tags, the library allows to load images from the local drawables folder or from the Internet.

This library is kept tiny without external dependencies.

How to import

Add this to your build.gradle:

repositories {
    jcenter()
}

dependencies {
    compile 'org.sufficientlysecure:html-textview:4.0'
}

Example

<org.sufficientlysecure.htmltextview.HtmlTextView
            android:id="@+id/html_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textAppearance="@android:style/TextAppearance.Small" />
HtmlTextView htmlTextView = (HtmlTextView) view.findViewById(R.id.html_text);

// loads html from string and displays cat_pic.png from the app's drawable folder
htmlTextView.setHtml("<h2>Hello wold</h2><ul><li>cats</li><li>dogs</li></ul><img src=\"cat_pic\"/>",
    new HtmlResImageGetter(htmlTextView));

or

HtmlTextView htmlTextView = (HtmlTextView) view.findViewById(R.id.html_text);

// loads html from string and displays cat_pic.png from the app's assets folder
htmlTextView.setHtml("<h2>Hello wold</h2><ul><li>cats</li><li>dogs</li></ul><img src=\"cat_pic\"/>",
    new HtmlAssetsImageGetter(htmlTextView));

or

HtmlTextView htmlTextView = (HtmlTextView) view.findViewById(R.id.html_text);

// loads html from string and displays http://www.example.com/cat_pic.png from the Internet
htmlTextView.setHtml("<h2>Hello wold</h2><img src=\"http://www.example.com/cat_pic.png\"/>",
    new HtmlHttpImageGetter(htmlTextView));

or

HtmlTextView htmlTextView = (HtmlTextView) view.findViewById(R.id.html_text);

// loads html from raw resource, i.e., a html file in res/raw/,
// this allows translatable resource (e.g., res/raw-de/ for german)
htmlTextView.setHtml(R.raw.help, new HtmlHttpImageGetter(htmlTextView));

or

<TextView
    android:id="@+id/html_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAppearance="@android:style/TextAppearance.Small" />
TextView htmlTextView = (TextView) view.findViewById(R.id.html_text);

// loads html from string and displays cat_pic.png from the app's drawable folder
Spanned formattedHtml = HtmlFormatter.formatHtml(new HtmlFormatterBuilder().setHtml("<h2>Hello wold</h2><ul><li>cats</li><li>dogs</li></ul><img src=\"cat_pic\"/>").setImageGetter(new HtmlResImageGetter(htmlTextView.getContext())));
htmlTextView.setText(formattedHtml);

Supported HTML tags

Tags supported by Android (history of Html class)

Extended support by HtmlTextView

  • <ul>
  • <ol>
  • <li>
  • <code>
  • <center>
  • <strike>

Support for HTML tables

HtmlTextView now supports HTML tables (to a limited extent) by condensing the text into a link which developers are able to render in a native WebView. To take advantage of the feature you'll need to:

  1. implement a ClickableTableSpan which provides access to the table HTML (which can be forwarded to a WebView)

  2. provide a DrawTableLinkSpan which defines what the table link should look like (i.e. text, text color, text size)

Take a look at the project's sample app for an example.

Support for A tag click listener

textView.setOnClickATagListener(new OnClickATagListener() {

    @Override
    public void onClick(View widget, @Nullable String href) {
        Toast.makeText(MainActivity.this, href, Toast.LENGTH_SHORT).show();
    }
});

We recognize the standard table tags:

  • <table>
  • <tr>
  • <th>
  • <td>

as well as the tags extended by HtmlTextView. However, support doesn’t currently extend to tags natively supported by Android (e.g. <b>, <big>, <h1>) which means tables will not include the extra styling.

Changelog

4.0

3.9

  • Add A tag click listener

3.8

  • Add HtmlFormatter for use with standard TextView

3.7

  • Fix #166
  • Migrated to AndroidX

3.6

  • Improve and fix indentions

3.5

  • Allow image compression

3.4

  • Fix textIsSelectable

3.3

  • Fix text cutting bug
  • Prevent EmptyStackException when processing malformed li tags

3.2

  • Indenting entries of ordered lists the same way as of unordered lists
  • Fix OutOfMemory

3.1

  • Override handling of <ul> <ol> and <li> tags done by newer versions of Android SDK (removes empty lines between items)

3.0

  • Removed deprecated methods and classes
  • Fix out of bounds issue

2.0

  • Introduce better API

License

Apache License v2

See LICENSE for full license text.

Authors

Contributions

Feel free to fork and do pull requests. I am more than happy to merge them. Please do not introduce external dependencies.

Comments
  • Image overlapping text with right-to-left

    Image overlapping text with right-to-left

    I start using your nice library. but i found an issue with images where the first image is shown very small and in case it is in the end of paragraph it overlaps the text. please see this image: screenshot_2015-12-31-00-49-43

    and this is the html for that text:

     "content": "<img src=\"http://www.alyemenialyoum.com/user_images/news/30-12-15-878636455.jpg\" alt=\"\"/>\n                    \n\n \n                    <p>سخرت المقاومة الشعبية بمحافظة تعز ، من الموالين لمليشيات الحوثي وصالح ، بعد انتشار مقطع فيديو لأحد عناصرهم يطلب من نجل المخلوع صالح  كبسولة عطر خاص .<p>وصنعت المقاومة في تعز مجموعة عطور مختلفة عليها شعارات حماسية ، للسخرية من الموالين للحوثي وصالح ، والاستفادة مادياً منها .<p>الجدير بالذكر ان ناشطون على مواقع التواصل الاجتماعية ، أطلقوا حملة سخرية من الموالين لمليشيات الحوثي وصالح ، بسبب الروائح القذرة التي تفوح منهم ، والاشكال التي يظهرون بها ، ومطالبتهم بفضلات زعيمهم عطراً لهم كما اسموها في خطوة تدل على قذرتهم والفئة التي ينتمون لها .</p>\r\n<p><img src=\"http://alyemenialyoum.com/user_images/news/30-12-15-505172948.jpg\"/></p>",
    
    bug 
    opened by Fshamri 10
  • Rudimentary table support

    Rudimentary table support

    This PR adds an imperfect workaround for adding table support by adding two spans: ClickableTableSpan and DrawTableLinkSpan.

    These spans provide limited table support by reconstructing the HTML and passing it to an app-defined implementation of ClickTableSpan (which could possibly forward it to a WebView similar to what's shown in the example).

    The DrawTableSpan does not need to be implemented, but we expose it so that applications can display text other than "[tap for table]", which is useful for localization.

    This PR is imperfect because once we start keeping track of a table tag, we are only able to keep track of other tags which android doesn't handle by default, so the raw html passed to the ClickableTableSpan won't necessarily be correct.

    opened by seato 9
  • <font size=3>  size is not working

    size is not working

    size is not working <p><font size="2" color="#999999">good morning~</font><font>999</font></p>

    bug 
    opened by helloHaifei 8
  • Nested UL tags not working

    Nested UL tags not working

    For some reason nested UL tags aren't rendering correctly. When I use a WebView, they render perfectly. Now, I've tried using WebViews but the performance has been terrible and I've even encountered app crashes.

    Here's a sample of my HTML.

    <ul>
        <li>Blah blah blah blah blah</li>
    </ul>
    <ul>
        <ul>
            <li>Blah blah blah blah blah</li>
        </ul>
    </ul>
    <ul>
        <ul>
            <li>Blah blah blah blah blah</li>
        </ul>
    </ul>
    <ul>
        <ul>
            <li>Blah blah blah blah blah</sup>
            </li>
        </ul>
    </ul>
    

    And what it should look like:

    • Blah blah blah blah blah
      • Blah blah blah blah blah
      • Blah blah blah blah blah
      • Blah blah blah blah blah

    Except I'm getting this:

    • No Compromise, Fully Capable
    • Seating for up to 7 passengers
    • Significantly updated exterior and interior
    • New Platinum trim level1

    Is there anything that I can do to get this working properly with your library ?

    EDIT: Fixed formatting.

    bug 
    opened by MoeHamoud 7
  • Use without imageGetter.

    Use without imageGetter.

    Is there is any way to apply html data only without image Getter? there will be no image tag in html data. In some cases we need only html data to be render on textView not images.

    enhancement 
    opened by naush-m 6
  • HTML.fromHtml adds space at end of text

    HTML.fromHtml adds space at end of text

    Html.fromHtml adds extra lines after the text. Html class looks at a

    tag, and append two "\n" chars to the end.

    see : http://stackoverflow.com/questions/11882323/html-fromhtml-adds-space-at-end-of-text

    bug 
    opened by benju69 6
  • PARAGRAPH span must start at paragraph boundary (no linebreak in li tags possible)

    PARAGRAPH span must start at paragraph boundary (no linebreak in li tags possible)

    java.lang.RuntimeException: PARAGRAPH span must start at paragraph boundary
                at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:604)
                at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:592)
                at android.text.HtmlToSpannedConverter.convert(Html.java:461)
                at android.text.Html.fromHtml(Html.java:138)
                at org.sufficientlysecure.htmltextview.HtmlTextView.setHtmlFromString(HtmlTextView.java:82)
    
    opened by msdx 6
  • NumberSpan wrong implementation

    NumberSpan wrong implementation

    Hello:

    NumberSpan implementation is leading to an exception:

    Fatal Exception: java.lang.AbstractMethodError
    
    abstract method "int android.text.ParcelableSpan.getSpanTypeIdInternal()"
    
    android.view.accessibility.AccessibilityNodeInfo.writeToParcel
    

    you may find a good explanation of the problem here:

    https://medium.com/@numan1617/android-framework-classes-choose-wisely-2f8300f6c255#.3669g6u0m

    opened by darienalvarez 5
  • Alignment error in <ul> & <ol>

    Alignment error in

    Hello, The <ul> or <ol> tags work perfectly if any one is used a single time. A successive use of any combination creates issue. Example: <ul>...</ul> (This will work as expected) <ul>...</ul> (This will give alignment issue). <ol>...</ol> (This will again work as expected) <ul>...</ul> (This will give alignment issue). <ul>...</ul> (This will again work as expected) <ol>...</ol> (This will get moved towards right by one space). <ol>...</ol> (This will again work as expected) <ol>...</ol> (This will get moved towards right by one space).

    So, successive <ol> just get shifted by one space without any other issue while, the bullets in <ul> get overlapped by the text.

    Check screen-shot. screenshot_20171028-065939 screenshot_20171028-070036 screenshot_20171028-070101 screenshot_20171028-070114

    bug 
    opened by XYZ-College-Forum 5
  • Formatting issue

    Formatting issue

    Hi,

    This is really great library. Thanks for making it.
    I have formatting issue when showing my HTML.

    HTML line has:

    <p>Heading &amp; Details are here</p>
                                                                     <ul>
                                                                     <li>db connection Error:An existing connection was forcibly closed by the remote host 10:54:23 Connection attempts: 1</li>
                                                                     <li>Point 2</li>
                                                                     <li>Point 3</li>
                                                                     <li>Point 4</li>
                                                                     <li>Point 5</li>
                                                                     <li>Point 6</li>
                                                                     </ul>
    

    The formatting is not that great: Any idea on why?

    image

    Screen shot above is from Nexus 5X.

    The code used:

    HtmlTextView hv = new HtmlTextView(Activity_New.this);
                                hv.setX(40);
                                hv.setHtml(htmldescription);
                               alert.setView(hv);
    

    I am not in a situation to use the web view hence I was looking for textFieldHTML solution.

    Can you let me know what could be wrong?

    opened by vijaykd 5
  • Tag center and tag font with color

    Tag center and tag font with color

    Work normal: <center><font color = #ff9800>LIST OF OBJECTS</font></center> Color wrong: <font color = #ff9800><center>LIST OF OBJECTS</center></font>

    opened by letuananh035 0
  • Table tag could show in HtmlTextView

    Table tag could show in HtmlTextView

    Tables cannot be displayed in textview, which is inconvenient. If users need to view the contents of tables, they can only switch to the next page。 Whether the table can be displayed in htmltextview?

    opened by joedan0104 1
  • Special Class for handling code snippets

    Special Class for handling code snippets

    There are many HTML files which have code snippets in them and need to display in a different way. They need to have line numbers and be horizontally scrollable. The code snippet could be associated with a particular class in the HTML tags such that it can be displayed easily.

    I am working with an app which needs the above and your library has helped me a lot to achieve it. But the main problem is of the improper code which is being displayed. So could there be a possible addition of it?

    screenshot_code

    opened by shivamsoods 0
  • Do not change the font.

    Do not change the font.

    I use the conductor framework in my project to replace fragment. I change the font in my project, but the font does not change only in the HtmlTextView.

    class MainActivity : AppCompatActivity() {
    
        private lateinit var router: Router
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            router = Conductor.attachRouter(this, container, savedInstanceState)
    
            if (!router.hasRootController())
                router.setRoot(RouterTransaction.with(HomeController()))
        }
    
        override fun onBackPressed() {
            if (!router.handleBack())
                super.onBackPressed()
        }
    }
    
    class HomeController : Controller() {
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
            val view = inflater.inflate(R.layout.controller_home, container, false)
            
            view.htmlTextView.setHtml("Hello <b>World</b> Hello")
    
            return view
        }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <org.sufficientlysecure.htmltextview.HtmlTextView
            android:id="@+id/htmlTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textSize="24sp" />
    </LinearLayout>
    

    Screenshot

    opened by TikTak123 0
Owner
Sufficiently Secure
Strengthening your freedom on Android
Sufficiently Secure
A simple and flexible Checked TextView or Checkable TextView

CheckableTextView Checkable TextView [KOTLIN] ⚡ A simple and flexible Checked TextView or Checkable TextView written in Kotlin ⚡ What's New Animation

null 110 Nov 20, 2022
MarkdownView is an Android webview with the capablity of loading Markdown text or file and display it as HTML, it uses MarkdownJ and extends Android webview.

MarkdownView is an Android webview with the capablity of loading Markdown text or file and display it as HTML, it uses MarkdownJ and extends Android webview.

Feras Alnatsheh 1k Dec 20, 2022
Mentions-TextView - Make Mentions and hashtags clickable in Textview

Mentions Textview Custome Textview with Mentions and hashtags being clickable. D

null 2 Jan 9, 2022
Simple way to create linked text, such as @username or #hashtag, in Android TextView and EditText

Simple Linkable Text Simple way to create link text, such as @username or #hashtag, in Android TextView and EditText Installation Gradle Add dependenc

Aditya Pradana Sugiarto 76 Nov 29, 2022
Animation effects to text, not really textview

HTextView Animation effects with custom font support to TextView see iOS Effects see Flutter Effects Screenshot type gif Scale Evaporate Fall Line Typ

hanks 5.5k Jan 5, 2023
Android's TextView that can expand/collapse like the Google Play's app description

ExpandableTextView ExpandableTextView is an Android library that allows developers to easily create an TextView which can expand/collapse just like th

Manabu S. 4k Dec 28, 2022
A library to show emoji in TextView, EditText (like WhatsApp) for Android

Discontinued This projected is discontinued. Please consider using other alternative, i.e EmojiCompat. Contact me if you want to continue working on a

Hieu Rocker 3.6k Jan 5, 2023
A TextView that automatically resizes text to fit perfectly within its bounds.

AutoFitTextView A TextView that automatically resizes text to fit perfectly within its bounds. Usage dependencies { compile 'me.grantland:autofitt

Grantland Chew 4.2k Jan 1, 2023
Android experiment showing a sinking TextView

Titanic is an Android experiment reproducing this effect.

Romain Piel 1.8k Dec 15, 2022
A Custom TextView with trim text

ReadMoreTextView A Custom TextView with trim text Download To add the ReadMoreTextView library to your Android Studio project, simply add the followin

Borja B. 1.7k Dec 29, 2022
Advanced Android TextView

Advanced Android TextView Companion app for my Advanced Android TextView talk, demostrating: Animated CompoundDrawable Text shadow Custom font Non-bre

Chiu-Ki Chan 1.2k Dec 9, 2022
AutoLinkTextView is TextView that supports Hashtags (#), Mentions (@) , URLs (http://), Phone and Email automatically detecting and ability to handle clicks.

AutoLinkTextView Deprecated Please use the new version of AutoLinkTextView AutoLinkTextView is TextView that supports Hashtags (#), Mentions (@) , URL

Arman 1.1k Nov 23, 2022
Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the brand new Roboto Slab fonts.

Android-RobotoTextView Implementation of a TextView and all its direct/indirect subclasses with native support for the Roboto fonts, includes the bran

Evgeny Shishkin 782 Nov 12, 2022
A TextView that simulates the effect from the app Secret where the characters fade in/out at different speeds.

SecretTextView A TextView that simulates the effect from the app Secret where the characters fade in/out at different speeds. How To Use Use it just l

Matt Kula 611 Nov 7, 2022
This is based on an open source autosizing textview for Android.

SizeAdjustingTextView This is based on an open source autosizing textview for Android I found a few weeks ago. The initial approach didn't resize mult

Elliott Chenger 255 Dec 29, 2022
An extension of Android's TextView, EditText and Button that let's you use the font of your choice

AnyTextView (deprecated) Note: AnyTextView is no longer being maintained. I recommend replacing AnyTextView with the Calligraphy library instead. Frus

Hans Petter Eide 165 Nov 11, 2022
Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Provides easy means to validate with dependencies.

android-formidable-validation Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Pr

Linden 147 Nov 20, 2022
Customized and Expandable TextView

Customized and Expandable TextView Simple library to change the Textview as rectangle, circle and square shapes by adding one line of code in xml file

Raja Gopal 62 Sep 22, 2022
Lightweight android library for highlighting sections of a textview, with optional callbacks.

Linker Lightweight android library for highlighting Strings inside of a textview (ignoring case), with optional callbacks. Language: Java MinSDK: 17 J

Josh Gainey 35 Apr 30, 2022