Skip to main content

How to display HTML in TextView?

How to display HTML in TextView? 


A1.


    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.

 For example (< Android Nougat):

   myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));

For example (>= Android Nougat):

   myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>",
                                                      Html.FROM_HTML_MODE_COMPACT));

A2. 

 
      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

Java

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



A3.

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



A4.

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



A5.


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






















Comments