12

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 )

Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • Does this answer your question? [How can I change the color of a part of a TextView?](https://stackoverflow.com/questions/4032676/how-can-i-change-the-color-of-a-part-of-a-textview) – Dmitrii Leonov Dec 28 '19 at 08:54

6 Answers6

15

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);
Amy
  • 4,034
  • 1
  • 20
  • 34
11

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)));
silentsudo
  • 6,730
  • 6
  • 39
  • 81
7

You can use

myTextView.setText(Html.fromHtml(stringB + "<font color=red>" + stringA + "</font>);
Collins Abitekaniza
  • 4,496
  • 2
  • 28
  • 43
6

You can use SpannableString is an excellent way to style strings in a TextView.

Demo

SO Post

Community
  • 1
  • 1
M D
  • 47,665
  • 9
  • 93
  • 114
0

You can either use HTML banners in your java class: Example:

 textElement.setText(Html.fromHtml("123456 <fontcolor='#FF0000'>789</font>"));

Or use CData format in your XML file: Example:

<string name="numbers"><![CDATA[123456<fontcolor="#FF0000">789</font>]]></string>

I hope that helped you ;)

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

You can use this.

textview.setText(Html.fromHtml(getString(R.string.stringname) + "" + " *" + "", Html.FROM_HTML_MODE_LEGACY));

Sriraksha
  • 459
  • 1
  • 8
  • 15