143
text = text + CepVizyon.getPhoneCode() + "\n\n"
            + getText(R.string.currentversion) + CepVizyon.getLicenseText();
    activationText.setText(text);   
myTextView.setText(text);

I want to change color for CepVizyon.getPhoneCode()'s string. How can I do this?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
atasoyh
  • 3,045
  • 6
  • 31
  • 57
  • See this: http://stackoverflow.com/questions/4897349/android-coloring-part-of-a-string-using-textview-settext – live-love Aug 05 '15 at 13:57
  • Possible duplicate of [Set color of TextView span in Android](http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android) – Suragch Jan 31 '17 at 07:17
  • That question was asked Jul 19 '10 at 16:27, about 3 months before yours. However, it is not always the oldest post that needs to be the duplicate target. The number of number of views, number of votes, number of answers, and clarity of the question should be taken into account. By marking this as a duplicate, it can help people find those other answers that also answer your question. – Suragch Feb 10 '17 at 09:27
  • Check this https://stackoverflow.com/a/57089362/6667442 – Ketan Ramani Jul 18 '19 at 07:38
  • To really understand what's behind the scenes, I always suggest to read an in-depth article like this one: https://medium.com/androiddevelopers/spantastic-text-styling-with-spans-17b0c16b4568 – Michal Vician Apr 06 '20 at 14:03

19 Answers19

211

Spannable is more flexible:

String text2 = text + CepVizyon.getPhoneCode() + "\n\n"
            + getText(R.string.currentversion) + CepVizyon.getLicenseText();

Spannable spannable = new SpannableString(text2);

spannable.setSpan(new ForegroundColorSpan(Color.WHITE), text.length(), (text + CepVizyon.getPhoneCode()).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(spannable, TextView.BufferType.SPANNABLE);
andy boot
  • 11,355
  • 3
  • 53
  • 66
  • 4
    Thank you for this answer! This is more like NSAttributedString in iOS :) To be even more flexible, replace text.lenght by text2.indexOf(CepVizyon.getPhoneCode()) which allow you to don't knowing the first part of the String. – iGranDav Feb 02 '12 at 10:34
  • 1
    You should put `()` after `text.length` as `length` is a method not a field. Would do it myself but edits must be of at least 6 characters :) – MSX Jun 23 '15 at 09:22
  • 1
    The problem with Spannable is that ellipsize=end doesn't work anymore. Which is a pretty serious problem in some cases. – Juan Carlos Ospina Gonzalez Nov 22 '16 at 09:28
  • 1
    Works just fine. Although creating an HTML string is advisable. And then parsing it via HTML class. `Html.fromHtml(R.id.your_html_string);` – sud007 Mar 07 '17 at 11:57
  • This changes color of underline (if textview has underline flag), any way to prevent that? – unlut Aug 26 '18 at 11:51
  • Why the need for "TextView.BufferType.SPANNABLE" ? It works without the second parameter... – android developer May 24 '23 at 13:09
112

If you have static text that needs color, you can add it without any code via the strings file:

<string name="already_have_an_account">Already have an account? <font color='#01C6DB'>Login</font></string>

then

<TextView
    android:layout_width="wrap_content"
    android:layout_height="64dp"
    android:text="@string/already_have_an_account"/>

result

enter image description here

I'm not sure which API versions this works on, but it doesn't work for API 19 that I've tested so far, so probably only some of the most recent API versions support this.

As @hairraisin mentioned in the comments, try using fgcolor instead of color for the font color, then it should work for lower API levels, but need more testing to be sure.

Null
  • 1,950
  • 9
  • 30
  • 33
Fonix
  • 11,447
  • 3
  • 45
  • 74
81
myTextView.setText(Html.fromHtml(text + "<font color=white>" + CepVizyon.getPhoneCode() + "</font><br><br>"
            + getText(R.string.currentversion) + CepVizyon.getLicenseText()));
Maneesh
  • 6,098
  • 5
  • 36
  • 55
25

Here solution in Kotlin that uses SpannableString to change color of part of a string.

    val phoneCodeColor = ContextCompat.getColor(this, R.color.myColor)
    val text = SpannableStringBuilder()
        .color(phoneCodeColor) { append("${ CepVizyon.getPhoneCode() }") }
        .append("\n\n")
        .append(getString(R.string.currentversion))
        .append(${ CepVizyon.getLicenseText() })

    activationText.text = text
    myTextView.text = text
Dmitrii Leonov
  • 1,331
  • 1
  • 15
  • 25
23

With regards to Maneesh's answer, this will work but you need to add and escape the quotes for the color attribute.

myTextView.setText(Html.fromHtml(text + "<font color=\"#FFFFFF\">" + CepVizyon.getPhoneCode() + "</font><br><br>"
            + getText(R.string.currentversion) + CepVizyon.getLicenseText()));
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
JoeLallouz
  • 1,338
  • 1
  • 10
  • 14
11

It is good for me!

            Spannable spannable = new SpannableString("ABC In-Network DEF");
            String str = spannable.toString();
            iStart = str.indexOf("In-Network");
            iEnd = iStart + 10;/*10 characters = in-network. */

            SpannableString ssText = new SpannableString(spannable);
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    //your code at here.
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(true);
                    ds.setColor(getResources().getColor(R.color.green));
                }
            };
            ssText.setSpan(clickableSpan, iStart, iEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mTextView.setText(ssText);
            mTextView.setMovementMethod(LinkMovementMethod.getInstance());
            mTextView.setHighlightColor(Color.TRANSPARENT);
            mTextView.setEnabled(true);
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
Anh Duy
  • 1,145
  • 15
  • 25
11

Here's a colorize function based on andyboot's answer:

 /**
 * Colorize a specific substring in a string for TextView. Use it like this: <pre>
 * textView.setText(
 *     Strings.colorized("The some words are black some are the default.","black", Color.BLACK),
 *     TextView.BufferType.SPANNABLE
 * );
 * </pre>
 * @param text Text that contains a substring to colorize
 * @param word The substring to colorize
 * @param argb The color
 * @return the Spannable for TextView's consumption
 */
public static Spannable colorized(final String text, final String word, final int argb) {
    final Spannable spannable = new SpannableString(text);
    int substringStart=0;
    int start;
    while((start=text.indexOf(word,substringStart))>=0){
        spannable.setSpan(
                new ForegroundColorSpan(argb),start,start+word.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        substringStart = start+word.length();
    }
    return spannable;
}
JohnnyLambada
  • 12,700
  • 11
  • 57
  • 61
9

Use character escapes + Html.fromHtml()

enter image description here

How to store the String in the string resource folder

<string name="textFromRes">
    &lt;font color="#FF0000">This is colored in red &lt;/font> This is not
</string>

How to show in TextView?

String text = this.getResources().getString(R.string.textFromRes);
htmlText.setText(Html.fromHtml(text));

Bonus:

The String in the output looks like this

<string name="textFromRes">
    &lt;font color="#FF0000">This is colored in red &lt;/font> This is not
    &lt;br /&gt;
    &lt;h1> This is h1 heading &lt;/h1>
    &lt;br /&gt;
    &lt;h3> This is h2 subheading&lt;/h3>
    &lt;br /&gt;
    &lt;b> This text is bold&lt;/b>
    &lt;br /&gt;
    &lt;i> This text is italic&lt;/i>
    &lt;br /&gt;
    Android users expect your app to look and behave in a way that is
    consistent with the platform. Not only should you follow material
    design guidelines for visual and navigation patterns,
    but you should also follow quality guidelines for compatibility,
    performance, security, and more.
    &lt;br /&gt;
    &lt;br /&gt;
    The following links provide everything you need to design a high quality Android app.
</string>
Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
8

I have made this little function, just pass in your text to color, the start and end indexes of what you want to color of that text and the color itself

Kotlin

   private fun colorMyText(inputText:String,startIndex:Int,endIndex:Int,textColor:Int):Spannable{
            val outPutColoredText: Spannable = SpannableString(inputText)
            outPutColoredText.setSpan(
                ForegroundColorSpan(textColor), startIndex, endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            return outPutColoredText
        }

Usage

txt_comment.text = colorMyText("Comentario: ${item.comentario}",0,13,Color.BLACK)
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
6

With a general-purpose Kotlin extension function, it would look like this:

/**
 * Change the color of a part of the text contained in this textView
 *
 * @param subStringToColorize has to already be set in the textView's text
 * @param colorResId
 */
fun TextView.colorize(subStringToColorize: String, @ColorRes colorResId: Int) {

  val spannable: Spannable = SpannableString(text)

  val startIndex = text.indexOf(subStringToColorize, startIndex = 0, ignoreCase = false)
  val endIndex = startIndex + subStringToColorize.length

  val color: Int = ContextCompat.getColor(context, colorResId)

  if (startIndex != -1) {
      spannable.setSpan(ForegroundColorSpan(color),
          startIndex,
          endIndex,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
      setText(spannable, TextView.BufferType.SPANNABLE)
   }
}
Alejandro H. Cruz
  • 507
  • 1
  • 7
  • 15
5

I didn't like the idea of doing this by code every time i want to color parts of the text which i have been doing a lot in all of my apps (and since in some case text is being set in runtime with different inline-defined colors) so i created my own MarkableTextView.

The idea was to:

  • Detect XML tags from string
  • Identify and match tag name
  • Extract and save attributes and position of text
  • Remove tag and keep content
  • Iterate through attributes and apply styles

Here's the process step by step:

First i needed a way to find XML tags in a given string and Regex did the trick..

<([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)(?:\s+([^>]*))?>([^>][^<]*)</\1\s*>

For the above to match an XML tag it has to have the following criteria:

  • Valid tag name like <a> <a > <a-a> <a ..attrs..> but not < a> <1>
  • Closing tag that has a matching name like <a></a> but not <a></b>
  • Any content, since there's no need to style "nothing"

Now for the attributes we're going to use this one..

([a-zA-Z]+)\s*=\s*(['"])\s*([^'"]+?)\s*\2

It has the same concept and generally i didn't need to go far for both since the compiler will take care of the rest if anything goes out of format.

Now we need a class that can hold the extracted data:

public class MarkableSheet {

    private String attributes;
    private String content;
    private int outset;
    private int ending;
    private int offset;
    private int contentLength;

    public MarkableSheet(String attributes, String content, int outset, int ending, int offset, int contentLength) {

        this.attributes = attributes;
        this.content = content;
        this.outset = outset;
        this.ending = ending;
        this.offset = offset;
        this.contentLength = contentLength;
    }

    public String getAttributes() {
        return attributes;
    }

    public String getContent() {
        return content;
    }

    public int getOutset() {
        return outset;
    }

    public int getContentLength() {
        return contentLength;
    }

    public int getEnding() {
        return ending;
    }

    public int getOffset() {
        return offset;
    }
}

Before anything else, we're going to add this cool iterator that i've been using for long to loop through matches (can't remember the author):

public static Iterable<MatchResult> matches(final Pattern p, final CharSequence input) {

        return new Iterable<MatchResult>() {

            public Iterator<MatchResult> iterator() {

                return new Iterator<MatchResult>() {

                    // Use a matcher internally.
                    final Matcher matcher = p.matcher(input);

                    // Keep a match around that supports any interleaving of hasNext/next calls.
                    MatchResult pending;

                    public boolean hasNext() {

                        // Lazily fill pending, and avoid calling find() multiple times if the
                        // clients call hasNext() repeatedly before sampling via next().
                        if (pending == null && matcher.find()) {
                            pending = matcher.toMatchResult();
                        }
                        return pending != null;
                    }

                    public MatchResult next() {

                        // Fill pending if necessary (as when clients call next() without
                        // checking hasNext()), throw if not possible.
                        if (!hasNext()) { throw new NoSuchElementException(); }

                        // Consume pending so next call to hasNext() does a find().
                        MatchResult next = pending;
                        pending = null;

                        return next;
                    }

                    /** Required to satisfy the interface, but unsupported. */
                    public void remove() { throw new UnsupportedOperationException(); }
                };
            }
        };
    }

MarkableTextView:

public class MarkableTextView extends AppCompatTextView {

    public MarkableTextView(Context context) {
        super(context);
    }

    public MarkableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MarkableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {

        // Intercept and process text
        text = prepareText(text.toString());

        super.setText(text, type);
    }

    public Spannable Markable;

    private Spannable prepareText(String text) {

        String parcel = text;
        Multimap<String, MarkableSheet> markableSheets = ArrayListMultimap.create();

        // Used to correct content position after tossing tags
        int totalOffset = 0;

        // Iterate through text
        for (MatchResult match : matches(Markable.Patterns.XML, parcel)) {

            // Get tag name
            String tag = match.group(1);

            // Match with a defined tag name "case-sensitive"
            if (!tag.equals(Markable.Tags.MARKABLE)) {

                // Break if no match
                break;
            }

            // Extract data
            String attributes = match.group(2);
            String content = match.group(3);

            int outset = match.start(0);
            int ending = match.end(0);
            int offset = totalOffset; // offset=0 since no preceded changes happened
            int contentLength = match.group(3).length();

            // Calculate offset for the next element
            totalOffset = (ending - outset) - contentLength;

            // Add to markable sheets
            MarkableSheet sheet =
                    new MarkableSheet(attributes, content, outset, ending, offset, contentLength);
            markableSheets.put(tag, sheet);

            // Toss the tag and keep content
            Matcher reMatcher = Markable.Patterns.XML.matcher(parcel);
            parcel = reMatcher.replaceFirst(content);
        }

        // Initialize spannable with the modified text
        Markable = new SpannableString(parcel);

        // Iterate through markable sheets
        for (MarkableSheet sheet : markableSheets.values()) {

            // Iterate through attributes
            for (MatchResult match : matches(Markable.Patterns.ATTRIBUTES, sheet.getAttributes())) {

                String attribute = match.group(1);
                String value = match.group(3);

                // Apply styles
                stylate(attribute,
                        value,
                        sheet.getOutset(),
                        sheet.getOffset(),
                        sheet.getContentLength());
            }
        }

        return Markable;
    }

Finally, styling, so here's a very simple styler i made for this answer:

public void stylate(String attribute, String value, int outset, int offset, int length) {

        // Correct position
        outset -= offset;
        length += outset;

        if (attribute.equals(Markable.Tags.TEXT_STYLE)) {

            if (value.contains(Markable.Tags.BOLD) && value.contains(Markable.Tags.ITALIC)) {

                Markable.setSpan(
                        new StyleSpan(Typeface.BOLD_ITALIC),
                        outset,
                        length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            else if (value.contains(Markable.Tags.BOLD)) {

                Markable.setSpan(
                        new StyleSpan(Typeface.BOLD),
                        outset,
                        length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            else if (value.contains(Markable.Tags.ITALIC)) {

                Markable.setSpan(
                        new StyleSpan(Typeface.ITALIC),
                        outset,
                        length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (value.contains(Markable.Tags.UNDERLINE)) {

                Markable.setSpan(
                        new UnderlineSpan(),
                        outset,
                        length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if (attribute.equals(Markable.Tags.TEXT_COLOR)) {

            if (value.equals(Markable.Tags.ATTENTION)) {

                Markable.setSpan(
                        new ForegroundColorSpan(ContextCompat.getColor(
                                getContext(),
                                R.color.colorAttention)),
                        outset,
                        length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            else if (value.equals(Markable.Tags.INTERACTION)) {

                Markable.setSpan(
                        new ForegroundColorSpan(ContextCompat.getColor(
                                getContext(),
                                R.color.colorInteraction)),
                        outset,
                        length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

And here's how the Markable class containing the definitions looks like:

public class Markable {

    public static class Patterns {

        public static final Pattern XML =
                Pattern.compile("<([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)(?:\\s+([^>]*))?>([^>][^<]*)</\\1\\s*>");
        public static final Pattern ATTRIBUTES =
                Pattern.compile("(\\S+)\\s*=\\s*(['\"])\\s*(.+?)\\s*\\2");
    }

    public static class Tags {

        public static final String MARKABLE = "markable";

        public static final String TEXT_STYLE = "textStyle";
        public static final String BOLD = "bold";
        public static final String ITALIC = "italic";
        public static final String UNDERLINE = "underline";

        public static final String TEXT_COLOR = "textColor";
        public static final String ATTENTION = "attention";
        public static final String INTERACTION = "interaction";
    }
}

All that we need now is to reference a string and basically it should look like this:

<string name="markable_string">
    <![CDATA[Hello <markable textStyle=\"underline\" textColor=\"interaction\">world</markable>!]]>
</string>

Make sure to wrap the tags with a CDATA Section and escape " with \.

I made this as a modular solution to process parts of the text in all different ways without the need of stuffing unnecessary code behind.

Explisam
  • 749
  • 13
  • 26
5

I did as andy boot said, but i had a clickable span as well, and it didn't work because the order the setSpans were called. So you have to first call the spannable.setSpan(clickableSpanand... then the spannable.setSpan(new ForegroundColorSpan... to get the color in the TextView

Tincho825
  • 829
  • 1
  • 13
  • 15
4

I created this little helper method that can be called from a TextView:

fun TextView.attributedString(
    forText: String,
    foregroundColor: Int? = null,
    style: StyleSpan? = null
) {
  val spannable: Spannable = SpannableString(text)

  // check if the text we're highlighting is empty to abort
  if (forText.isEmpty()) {
    return
  }

  // compute the start and end indices from the text
  val startIdx = text.indexOf(forText)
  val endIdx = startIdx + forText.length

  // if the indices are out of bounds, abort as well
  if (startIdx < 0 || endIdx > text.length) {
    return
  }

  // check if we can apply the foreground color
  foregroundColor?.let {
    spannable.setSpan(
        ForegroundColorSpan(it),
        startIdx,
        endIdx,
        Spannable.SPAN_INCLUSIVE_EXCLUSIVE
    )
  }

  // check if we have a stylespan
  style?.let {
    spannable.setSpan(
        style,
        startIdx,
        endIdx,
        Spannable.SPAN_INCLUSIVE_EXCLUSIVE
    )
  }

  // apply it
  text = spannable
}

To use it:

plateText.text = "Hello world!"

// This will color the part "world" to whatever color you have defined
// And make the word **bold**.
plateText.attributedString(
   "world",
   getColor(R.color.colorMatchingText, null),
   StyleSpan(Typeface.BOLD)
)

Tested on API 29, cheers!

KBog
  • 3,800
  • 1
  • 25
  • 31
3

Inspired by Alejandro H. Cruz's answer above.

His function only works for a single substring match, I have updated his method to use Regex and should update colors on all matches:

fun TextView.colorizeAll(subStringToColorize: String, @ColorRes colorResId: Int) {

    val color: Int = ContextCompat.getColor(context, colorResId)

    val spannable: Spannable = SpannableString(text)

    val pattern = subStringToColorize.toRegex()

    val matches = pattern.findAll(text, 0)

    matches.forEach { match ->

        val startIndex = match.range.first

        val endIndex = match.range.last + match.range.step

        spannable.setSpan(ForegroundColorSpan(color),
                startIndex,
                endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        setText(spannable, TextView.BufferType.SPANNABLE)

    }
}
eppe
  • 51
  • 2
3
SpannableStringBuilder builder = new SpannableStringBuilder();

    String the = "The ";
    SpannableString theSpannable= new SpannableString(the);
    builder.append(theSpannable);
    String author = "author ";
    SpannableString authorSpannable= new SpannableString(author);
    authorSpannable.setSpan(new RelativeSizeSpan(1.2f), 0,authorSpannable.length(), 0); // set size
    authorSpannable.setSpan(new ForegroundColorSpan(Color.BLACK), 0, authorSpannable.length(), 0);
    builder.append(authorSpannable);
    String has = "has ";
    SpannableString hasSpannable= new SpannableString(has);
    builder.append(hasSpannable);

    String approved = "approved ";
    SpannableString approvedSpannable= new SpannableString(approved);
    approvedSpannable.setSpan(new RelativeSizeSpan(1.2f), 0,approvedSpannable.length(), 0); // set size
    StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
    approvedSpannable.setSpan(boldSpan, 0, approvedSpannable.length() + 0, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    approvedSpannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.CLR_PRESSED_SAVED)), 0,
            approvedSpannable.length(), 0);
    builder.append(approvedSpannable);

    String white = "your access to this share. Do you want re-access now?";
    SpannableString whiteSpannable= new SpannableString(white);
    builder.append(whiteSpannable);
    _AccessStatusText.setText(builder, TextView.BufferType.SPANNABLE);
Vega
  • 27,856
  • 27
  • 95
  • 103
2

its Simple

    String text = "We've sent the code to ";
    String text2 = text + getEmail() + "\n\n";
    Spannable spannable = new SpannableString(text2);
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), text.length(), (text + getEmail()).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    mBinding.textViewStatus.setText(spannable, TextView.BufferType.SPANNABLE);
MohammadReza
  • 154
  • 1
  • 11
1

DO NOT USE Html.fromHtml to avoid fragmented behavior. Spannable or SpannableStringBuilder is the best way to do this with ForegroundColorSpan or BackgroundColorSpan depending on your requirements. Html or HtmlCompat tag even with style color or background-color is not realiable as it does not work on all SDK specially on lower version such as 21, same case for emojis.

Example case:

<span style=\"background-color:red\">&#11014;</span>

When the Html string above converts to Spanned using HtmlCompat.fromHtml and use it in setText() the style does not work on older SDK version.

Mihae Kheel
  • 2,441
  • 3
  • 14
  • 38
0

If you want to change a part of the text to the color you want, just put your text instead of "Masoud" or "Siahkali" and enter the color you want in the "color" section.

String text = "My name is <font color='#EE0000'> Masoud </font> and my family is <font color='#EE0000'> Siahkali </font> "
textView.setText(Html.fromHtml(text));
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Apr 11 '23 at 09:37
-5

One way is to split myTextView to few separate TextViews, one of which would be only for phone code. Then controlling color of this specific TextView is pretty straight-forward.

Ralkie
  • 3,736
  • 3
  • 25
  • 25