Is it possible to set multiple styles for different pieces of text inside a TextView?
For instance, I am setting the text as follows:
tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);
Is it possible to have a different style for each text element? E.g., line1 bold, word1 italic, etc.
The developer guide's Common Tasks and How to Do Them in Android includes Selecting, Highlighting, or Styling Portions of Text:
// Get our EditText object. EditText vw = (EditText)findViewById(R.id.text); // Set the EditText's text. vw.setText("Italic, highlighted, bold."); // If this were just a TextView, we could do: // vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE); // to force it to use Spannable storage so styles can be attached. // Or we could specify that in the XML. // Get the EditText's internal text storage Spannable str = vw.getText(); // Create our span sections, and assign a format to each. str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
But that uses explicit position numbers inside the text. Is there a cleaner way to do this?
It is more light weight to use a
SpannableString
instead of html markup. It helps me to see visual examples so here is a supplemental answer.This is a single
TextView
.Further Study
This example was originally inspired from here.
If you want to be able to add the styled text in xml you can create a custom view extending TextView and override setText():
Then, you can use it like this (replace
PACKAGE_NAME
with your package name):If you don't feel like using html, you could just create a styles.xml and use it like this:
In fact, except the Html object, you also could use the Spannable type classes, e.g. TextAppearanceSpan or TypefaceSpan and SpannableString togather. Html class also uses these mechanisms. But with the Spannable type classes, you've more freedom.
Using an auxiliary Spannable Class as Android String Resources shares at the bottom of the webpage. You can approach this by creating
CharSquences
and giving them a style.But in the example they give us, is just for bold, italic, and even colorize text. I needed to wrap several styles in a
CharSequence
in order to set them in aTextView
. So to that Class (I named itCharSequenceStyles
) I just added this function.And in the view I added this.
I hope this help you!
Slightly off-topic, but I found this too useful not to be mentioned here.
What if we would like to read the the Html text from string.xml resource and thus make it easy to localize. CDATA make this possible:
From our Java code we could now utilize it like this:
I did not expect this to work. But it did.
Hope it's useful to some of you!