[android] Html.fromHtml deprecated in Android N

I am using Html.fromHtml to view html in a TextView.

Spanned result = Html.fromHtml(mNews.getTitle());
...
...
mNewsTitle.setText(result);

But Html.fromHtml is now deprecated in Android N+

What/How do I find the new way of doing this?

This question is related to android deprecated android-7.0-nougat

The answer is


If you are lucky enough to develop on Kotlin, just create an extension function:

fun String.toSpanned(): Spanned {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
    } else {
        @Suppress("DEPRECATION")
        return Html.fromHtml(this)
    }
}

And then it's so sweet to use it everywhere:

yourTextView.text = anyString.toSpanned()

Just to extend the answer from @Rockney and @k2col the improved code can look like:

@NonNull
public static Spanned fromHtml(@NonNull String html) {
    if (CompatUtils.isApiNonLowerThan(VERSION_CODES.N)) {
        return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
        //noinspection deprecation
        return Html.fromHtml(html);
    }
}

Where the CompatUtils.isApiNonLowerThan:

public static boolean isApiNonLowerThan(int versionCode) {
    return Build.VERSION.SDK_INT >= versionCode;
}

The difference is that there are no extra local variable and the deprecation is only in else branch. So this will not suppress all method but single branch.

It can help when the Google will decide in some future versions of Android to deprecate even the fromHtml(String source, int flags) method.


You can use

//noinspection deprecation
return Html.fromHtml(source);

to suppress inspection just for single statement but not the whole method.


Or you can use androidx.core.text.HtmlCompat:

HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)

HtmlCompat docs


Compare of the flags of fromHtml().

<p style="color: blue;">This is a paragraph with a style</p>

<h4>Heading H4</h4>

<ul>
   <li style="color: yellow;">
      <font color=\'#FF8000\'>li orange element</font>
   </li>
   <li>li #2 element</li>
</ul>

<blockquote>This is a blockquote</blockquote>

Text after blockquote
Text before div

<div>This is a div</div>

Text after div

FROM_HTML FLAGS


Try the following to support basic html tags including ul ol li tags. Create a Tag handler as shown below

import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.TagHandler;
import android.util.Log;

public class MyTagHandler implements TagHandler {
    boolean first= true;
    String parent=null;
    int index=1;
    @Override
    public void handleTag(boolean opening, String tag, Editable output,
                          XMLReader xmlReader) {

        if(tag.equals("ul")) parent="ul";
        else if(tag.equals("ol")) parent="ol";
        if(tag.equals("li")){
            if(parent.equals("ul")){
                if(first){
                    output.append("\n\t•");
                    first= false;
                }else{
                    first = true;
                }
            }
            else{
                if(first){
                    output.append("\n\t"+index+". ");
                    first= false;
                    index++;
                }else{
                    first = true;
                }
            }
        }
    }
}

Set the text on Activity as shown below

@SuppressWarnings("deprecation")
    public void init(){
        try {
            TextView help = (TextView) findViewById(R.id.help);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                help.setText(Html.fromHtml(getString(R.string.help_html),Html.FROM_HTML_MODE_LEGACY, null, new MyTagHandler()));
            } else {
                help.setText(Html.fromHtml(getString(R.string.help_html), null, new MyTagHandler()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

And html text on resource string files as

<![CDATA[ ...raw html data ...]] >


From official doc :

fromHtml(String) method was deprecated in API level 24. use fromHtml(String, int) instead.

  1. TO_HTML_PARAGRAPH_LINES_CONSECUTIVE Option for toHtml(Spanned, int): Wrap consecutive lines of text delimited by '\n' inside <p> elements.

  2. TO_HTML_PARAGRAPH_LINES_INDIVIDUAL Option for toHtml(Spanned, int): Wrap each line of text delimited by '\n' inside a <p> or a <li> element.

https://developer.android.com/reference/android/text/Html.html


just make a function :

public Spanned fromHtml(String str){
  return Build.VERSION.SDK_INT >= 24 ? Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY) : Html.fromHtml(str);
}

The framework class has been modified to require a flag to inform fromHtml() how to process line breaks. This was added in Nougat, and only touches on the challenge of incompatibilities of this class across versions of Android.

I've published a compatibility library to standardize and backport the class and include more callbacks for elements and styling:

https://github.com/Pixplicity/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);

Here is my solution.

 if (Build.VERSION.SDK_INT >= 24) {
        holder.notificationTitle.setText(Html.fromHtml(notificationSucces.getMessage(), Html.FROM_HTML_MODE_LEGACY));
    } else {
        holder.notificationTitle.setText(Html.fromHtml(notificationSucces.getMessage()));

    }

If you're using Kotlin, I achieved this by using a Kotlin extension:

fun TextView.htmlText(text: String){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY))
    } else {
        setText(Html.fromHtml(text))
    }
}

Then call it like:

textView.htmlText(yourHtmlText)

I had a lot of these warnings and I always use FROM_HTML_MODE_LEGACY so I made a helper class called HtmlCompat containing the following:

   @SuppressWarnings("deprecation")
   public static Spanned fromHtml(String source) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
        } else {
            return Html.fromHtml(source);
        }
    }

fromHtml

This method was deprecated in API level 24.

You should use FROM_HTML_MODE_LEGACY

Separate block-level elements with blank lines (two newline characters) in between. This is the legacy behavior prior to N.

Code

if (Build.VERSION.SDK_INT >= 24)
        {
            etOBJ.setText(Html.fromHtml("Intellij \n Amiyo",Html.FROM_HTML_MODE_LEGACY));

         }
 else
        {
           etOBJ.setText(Html.fromHtml("Intellij \n Amiyo"));
        }

For Kotlin

fun setTextHTML(html: String): Spanned
    {
        val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
        } else {
            Html.fromHtml(html)
        }
        return result
    }

Call

 txt_OBJ.text  = setTextHTML("IIT Amiyo")