I am trying to add lines with different colors to my TextView using html tags.
For whatever reason,
Html.fromHtml("<font color='#145A14'>text</font>");
won't show up colored in the TextView.
I am trying to add lines with different colors to my TextView using html tags.
For whatever reason,
Html.fromHtml("<font color='#145A14'>text</font>");
won't show up colored in the TextView.
My answer involves guesswork about your code, but here goes:
When you use the font tag: DO NOT include an alpha channel so that your hex string looks like "#ff123456". If you use Integer.toHexString(), you will have an alpha channel in that result.
It worked when i used substring(2) on my hex string from rescource.
To sum up:
text.setText(Html.fromHtml("<font color='#123456'>text</font>"));
will work, but:
text.setText(Html.fromHtml("<font color='#ff123456'>text</font>"));
won't!
The fromHtml method is extremely limited in terms of the HTML tags that it supports, and font is not one of them. See http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html for an unofficial list. I did some research on this myself, and I found that fromHtml is based on an obscure and poorly documented rendering engine.
I use this code
Html.fromHtml(convertToHtml("<font color='#145A14'>text</font>"));
public String convertToHtml(String htmlString) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<![CDATA[");
stringBuilder.append(htmlString);
stringBuilder.append("]]>");
return stringBuilder.toString();
}
That looks like a very dark color, are you sure that your screen is capable to display such colors, so you can distinguish them from black? The code snippet looks good, I've tried similar code many times and it worked like a charm. Try it with somewhat brighter, i.e. #ff0000 (red), to verify that it works:
TextView text = ... // find or instantinate your text view.
text.setText(Html.fromHtml("<font color='#ff0000'>text</font>"));
txt_description1.setText(Html.fromHtml("<font color='rgb'>"+str_description1+"</font>"));
If you do not want a single static color and want to directly reflect from editor you can use "rgb". It will reflect the exact color what you have set in editor, just set in textview
and concat
it with textview value.
And you are all set to go.
For color text with hyperlink URL:
textView.setText(Html.fromHtml("You agree to our <font color='#F20000'><a href='https://www.yoururl.com'> Terms of Service</a></font> and <font color='#F20000'><a href='https://www.yoururl.com'>Privacy Policy</a></font>", Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
This worked for me and I am sure it will also work for all.