views:

338

answers:

1

Is it possible to style a single, say, TextView in Android with multiple alternating styles, colors, and sizes? Think inline HTML or CSS but in the Android world.

As an extreme, to demonstrate the point, let's say I wanted to have a word "CIRCUS" with each letter a being different color. Do I have to create 6 TextViews for this or can this be done in one?

Thanks.

+2  A: 

I don't think there is something inherent in the View that allows for defining several different styles to be applied to different parts of the View, but you can apply different markup within a View through Spannables.

It isn't a very general solution, but at least for TextViews, the setText method accepts a spanned string.

David Hedlund
Thank you - I was not aware of the Spannables. They remind me of <span> or <div> tags and related CSS properties. I just found a recipe in the Android SDK API doc itself: http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext.
Artem Russakovskii
But holy crap - is this approach absolutely horrible and ugly or what? What is this - 1995?
Artem Russakovskii
Additionally, it looks like string resources can be styled individually without tricks: "If you use a string resource, you can add some simple styling, such as bold or italic using HTML notation. The currently supported tags are: B (bold), I (italic), U (underline), TT (monospace), BIG, SMALL, SUP (superscript), SUB (subscript), and STRIKE (strikethrough). So, for example, in res/values/strings.xml you could declare this:<resource> <string>id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string></resources>"
Artem Russakovskii
well, yes, you can use HTML, but to get that to show up properly in a TextView, you'd have to do `myTextView.setText(Html.fromHtml(myHtmlString))` and `fromHtml` returns a SpannedString, so that's actually the exact same approach
David Hedlund