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?
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?
Try the following to support basic html tags including ul ol li tags. Create a Tag handler as shown below
Set the text on Activity as shown belowAnd html text on resource string files as
<![CDATA[ ...raw html data ...]] >
If you are lucky enough to develop on Kotlin, just create an extension function:
And then it's so sweet to use it everywhere:
If you're using Kotlin, I achieved this by using a Kotlin extension:
Then call it like:
Or you can use
androidx.core.text.HtmlCompat
:HtmlCompat docs
You have to add a version check and use the old method on Android M and below, on Android N and higher you should use the new method. If you don't add a version check your app will break on lower Android versions. You can use this method in your Util class.
Flag parameters:
You can read more about the different flags on the Html class documentation
Just to extend the answer from @Rockney and @k2col the improved code can look like:
Where the
CompatUtils.isApiNonLowerThan
: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.