I am developing an Android app. In my app, I am trying to set different colors to text in a TextView
. I mean multiple colors in a TextView
. I am trying to use Html.fromHtml
to do it. But it is not working. Please see my code below:
TextView
xml:
<TextView
android:paddingTop="@dimen/general_line_spacing"
android:paddingBottom="@dimen/general_line_spacing"
android:textSize="@dimen/mm_item_title_size"
android:textColor="@color/colorPrimaryText"
android:id="@+id/mm_item_tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This is how I set text to TextView
String title = post.getTitle();
if(title!=null && title.length()>MAX_TITLE_LENGTH)
{
title = title.substring(0, MAX_TITLE_LENGTH);
title = title + "<font color='color:#2bb1ff'> .... read more</font>";
}
viewHolder.tvTitle.setText(Html.fromHtml(title));
As you can see, I am setting font color using html. But it is not working. "read more" text appended is always just the same color with other letters. So I tried this way too.
title = title + "<![CDATA[<font color='color:#2bb1ff'> .... read more</font>]]>";
It is not working. This also:
title = title + "<span style=color:'#2bb1ff'> .... read more</span>";
So how can I set multiple colors to text in a TextView
please? Why my code is not working? How can I fix it?
Try this
title = title + "<font color=#2bb1ff> .... read more</font>";
Try to use it like that:
title = title + "<span style='color: #2bb1ff;'> .... read more</span>";
Use Spannable like this :
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString str1 = new SpannableString(titleText);
builder.append(str1);
SpannableString str2 = new SpannableString("....read more");
str2.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getActivity(), R.color.colorGrey)), 0, str2.length(), 0);
builder.append(str2);
viewHolder.tvTitle.setText(builder);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With