6

I have a spannable string containing bold italics and underlined text ( it may contain more formatted text ) For Example : - abcdef dfdfdfdf dfgdfgfdgf dfgfdgdfgfdfgd

I want to convert this string into html formatted text such that, my final output contains tags such that the above string should become

abcdef dfdfdfdf dfgdfgfdgf dfgfdgdfgfdfgd

TextUtils.htmlEncode

is not working. Real World Scenario - You view a webpage and when you view its source it contains tags. Similar thing i want here

Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66

2 Answers2

6

this is how to convert string to html but consider not all html tags working on android .

Spanned htmlText = Html.fromHtml(text);
mytextView.setText(htmlText);

android supported only this html tags

<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>
Noob
  • 2,857
  • 6
  • 33
  • 47
  • It seams that other tag work to such as > and < for > and <. And there is a bug as < is interpreted as a start tag and not as a lower than sign. see https://stackoverflow.com/questions/58718421/android-how-to-espape-a-greater-than-sign-in-html-fromhtml-which-is-unders/58718627#58718627 – Nathalie Nov 05 '19 at 20:18
  • "Too many characters in character literal" error – Fernando Torres Mar 10 '21 at 21:46
5

You need to use Html.toHtml() to convert your Spanned text into HTML string.

String htmlString = Html.toHtml(spannedText);
waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • 1
    If i use this, then if i have **dfd** in my spannable string, then the html is returned as `dfd`. I want that it should return dfd. Is there any way to achieve this ? – Rahul Gupta Nov 06 '13 at 07:08
  • i think that's totally up to how the `Html.toHtml` method does the conversion. However what you may do is to use `htmlString.replace("", "");` to simplify the tags. Its a hack but will resolve this particular issue. – waqaslam Nov 06 '13 at 08:10
  • Ya did this only. Thanks anyway :) – Rahul Gupta Nov 06 '13 at 08:33