Mayuri Joshi
Mayuri Joshi

Reputation: 164

Set TextView's portion of text color?

I want to set color to portion of text using Html.fromHtml() method.

My code is

String name =  "<font color=\"#B034A2\">" + notificationListBean.getUsername() + "</font>"
textview.setText(Html.fromHtml(name));

But textcolor is not changed.

I also tried this but this also not working

Spannable wordtoSpan = new SpannableString(name);        
wordtoSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.noti_color)), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

textview.setText(wordtoSpan);

What changes should i do?

Upvotes: 0

Views: 120

Answers (3)

Shayan_Aryan
Shayan_Aryan

Reputation: 2042

Spannable wordtoSpan = new SpannableString(name);        
wordtoSpan.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.noti_color)), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(wordtoSpan);

This code you're just using should work. I doupt the color. Test it with a simple color & fixed range:

wordtoSpan.setSpan(new ForegroundColorSpan(Color.Red), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Upvotes: 0

Manikanta
Manikanta

Reputation: 3421

Yesterday i have faced same problem with Html.fromHtml() so i have used spannable string here is how i will edit your code

SpannableStringBuilder builder = new SpannableStringBuilder();

                SpannableString carOwnerSpannable= new SpannableString("Mayuri");
                carOwnerSpannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(JobDetailTabbedActivity.this,R.color.colorAccent)), 0, carOwnerName.length(), 0);
                builder.append(carOwnerSpannable);

                builder.append(" | LastName:Joshi");

                textView.settext(builder);

comment below if this doesn't work.

Expected Output:

Mayuri(in green color(my color accent is green)) | LastName:Joshi(In white)

add <color name="colorAccent">#1AB394</color> to colors.xml

Upvotes: 1

cw fei
cw fei

Reputation: 1564

Try:

textView.setText(Html.fromHtml(name), TextView.BufferType.SPANNABLE);

Upvotes: 1

Related Questions