android – Rich text in a textview-ThrowExceptions

Exception or error:

I need create an “Info” for my program. I’d like fill the info text with several colors, style, fonts, ecc.

I found this: http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring

is there another way (better easy) to do this?

thanks!

How to solve:

Upon reading your question title, I was prepared to give you a link to that exact article. I’ve found using spans and SpannableString to be quite powerful. The alternate would be to use HTML formatting for your text, which can be done with Html.fromHtml().

However, It’s not exactly clear which HTML tags are supported, since the documentation simply reads:

This class processes HTML strings into displayable styled text. Not
all HTML tags are supported.

So, for a good solution, I would definitely go with the SpannableString approach in the article. This method is very handy in practice since you can also make your own span classes that extend the existing ones (for example, if you want to have a section of text use a custom font that isn’t built in).

###

I wrote a library over the weekend that handles this, I called it a RichTextView.

The library allows you to format a span of text (make it bold, underline, italic, combination, etc) as well as color it (text color and highlight). In the next release I plan to allow for custom font spans and such as well.

To use it is simple, just add the following dependency to your gradle file:

compile 'com.androidessence.lib:richtextview:1.0.1'

Now, let’s say you want to make the first four characters bold, you can simply make the following call:

myRichTextView.formatSpan(0, 4, RichTextView.FormatType.BOLD);

Notice that the end index parameter is not inclusive, so by saying (0 -> 4) we are actually bolding indexes (0 -> 3).

If you would like to do both bold and underline, use an EnumSet:

myRichTextView.formatSpan(0, 4, EnumSet.of(RichTextView.FormatType.BOLD, RichTextView.FormatType.UNDERLINE));

For the latest information please see the Github repository linked above, though I will try to update this answer any time it becomes outdated.

###

When I have needed formatted text in the past, I have created an html file with formatting, stuck it in the res/raw directory and loaded that into a WebView. I have never tried it with different fonts before though so not sure if that will work, but bold and italics, etc will work.

Leave a Reply

Your email address will not be published. Required fields are marked *