Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text color of the part of the TextView?

Tags:

android

I have simple textView controler on my application.
On this textView i set the text "123456789" - the text color is black.

I want that the three last digit ( 789 ) will be shown with red text color.

Is there any simple way to do it without using two textView controls
(one will contain "123456" in black and second will contain "789" in red )

like image 303
Yanshof Avatar asked Nov 18 '15 06:11

Yanshof


2 Answers

You can use this method

public static final Spannable getColoredString(Context context, CharSequence text, int color) {
        Spannable spannable = new SpannableString(text);
        spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannable;
    }

then later you call is by using

textview.append(getColoredString(this, "Hi!", ContextCompact.getColor(this, R.color.red)));
textview.append(getColoredString(this, "User", ContextCompact.getColor(this, R.color.green)));
like image 100
silentsudo Avatar answered Oct 01 '22 21:10

silentsudo


Try This:

Set TextView as a HTML using SpannableTextView

String text = "<font color='black'>123456</font><font color='red'>789</font>";
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
like image 37
Amy Avatar answered Oct 01 '22 22:10

Amy