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?
尝试这个
title = title + "<font color=#2bb1ff> .... read more</font>";
尝试像这样使用它:
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);
Hope this will help you:
title = title + "![CDATA[<font color=#2bb1ff> .... read more</font>]]"
Note: Please don't use static text in code. try to use it on string.xml file then get it from there. Example:
<string name="read_more"><![CDATA[<font color=#2bb1ff> .... read more</font>]]></string>
title = title + activity.getResources().getString(R.string.read_more);
I've checked in my application that's code working.
title = title + "<font color='#000'> .... read more</font>";
txt_view.setText(Html.fromHtml(title));
Please check carefully in your code may be your title is null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.