Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting color using Html.fromHtml to TextView in Android is not working

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?

like image 746
Wai Yan Hein Avatar asked Dec 19 '16 08:12

Wai Yan Hein


3 Answers

Try this

title = title + "<font color=#2bb1ff> .... read more</font>";
like image 155
ShekharKG Avatar answered Nov 17 '22 13:11

ShekharKG


Try to use it like that:

title = title + "<span style='color: #2bb1ff;'> .... read more</span>";
like image 36
arnas120 Avatar answered Nov 17 '22 13:11

arnas120


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);
like image 2
Meenal Avatar answered Nov 17 '22 14:11

Meenal