Pentium10
Pentium10

Reputation: 208002

What options I have to show a sentence parts with different color?

I have a longer sentence >200 characters. I need to show on the screen having parts of them in different color, like highlighting search results, each with different color. The text should auto wrap with screen width, and have no break sections between parts. I meant with this that I can put sections on a new line. They will have to continue the previous section, only wrap when the screen is off.

The best would be an EditText, as I need to allow editing also, but I am wondering I am able to change the color of various sentence parts, or just as a whole.

What do you think, with what UI elements can I achieve this view?

Upvotes: 2

Views: 491

Answers (2)

Edward Falk
Edward Falk

Reputation: 10103

See http://developer.android.com/reference/android/text/Spannable.html

You can also use limited html-like markup in text resources, in which case the resource will be compiled into a Spannable. The tags <i>, <b>, <tt>, <big>, <small>, <strike>, <u>, <sup>, <sub>, <li>, <marquee>, <font fgcolor= bgcolor= height= size=>, <a href=>, <annotation name=> are all accepted. There may be others, but if they're not documented, they're probably not safe to use. See StringBlock.java

I couldn't find any official documentation on the Html class, but the docstrings in text/Html.java are helpful. The class seems to be public enough. Thanks for pointing this out Sebi.

Upvotes: 1

RoflcoptrException
RoflcoptrException

Reputation: 52249

There are more or less two different way to achieve that:

1) The, I think, official way, using Spannable:

http://developer.android.com/reference/android/text/Spannable.html

With Spannable you can do something like this:

Spannable spannable = (Spannable) yourTextView.getText();
spannable.setSpan(new BackgroundColorSpan(0xFF0000), startPosition, endPosition, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

There are different Spannables like BackgroundColorSpan that i used in the example code. The Flags are explained here and in this package you can find the different Spannable possibilities.

2) A much easier way, but more or less undocumented way is to use HTML tags. You can for example use code like this:

String textString ="<font color='#ff0000' > <b>hello</b> </font>"

yourTextView.setText(Html.fromHtml(textString)) 

I'm not sure which HTML tags are supported. And I dont know a documentation of this, so I think you just have to try. But at least bold font and colored font is working in the code I'm using in my application.

Upvotes: 6

Related Questions