Skip to content Skip to sidebar Skip to footer

How To Generate Styled Text For Textview While Assembling String?

I have a TextView that will hold a styled, multiline string. This text is generated line by line as the data is drawn from different sources bit by bit. As I grab each field, I a

Solution 1:

Mark your string up with <b> and <i> tags as appropriate and then use the Html.fromHtml(String) to return the Spannable you are looking for.

Solution 2:

Html.fromHtml(String) carries a lot more baggage with it than the more light weight SpannableString classes. Whenever possible I would recommend that you avoid fromHtml to style a string.

In your case you could build the string with SpannableStringBuilder and then set the TextView text with the final styled string.

// set the textSpannableStrings1=newSpannableString("Due Date\n");
SpannableStrings2=newSpannableString("July 22, 2010\n");
SpannableStrings3=newSpannableString("Course\n");
SpannableStrings4=newSpannableString("CSC 350\n");

// set the style
s1.setSpan(newStyleSpan(Typeface.BOLD), 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s2.setSpan(newStyleSpan(Typeface.ITALIC), 0, s2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s3.setSpan(newStyleSpan(Typeface.BOLD), 0, s3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s4.setSpan(newStyleSpan(Typeface.ITALIC), 0, s4.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// build the stringSpannableStringBuilderbuilder=newSpannableStringBuilder();
builder.append(s1);
builder.append(s2);
builder.append(s3);
builder.append(s4);

// set the text view with the styled text
textView.setText(builder);

I set the text and styles one by one but in real usage this could easily be done in a loop. Here is the result:

enter image description here

Solution 3:

you can use this:

textview.setTypeface(null, Typeface.BOLD_ITALIC);

Solution 4:

You can set a Spannable as the text of the TextView. That way you can create your text first, add style info when needed, and put that into the TextView as appropriate.

Solution 5:

You should check how HTML class does it. I would parse the input and generate the spannable on the fly.

Post a Comment for "How To Generate Styled Text For Textview While Assembling String?"