18

I am trying to change the color of certain words (Search results) in a TextView? I tried to use ANSI colors like this:

text.setText("\u001B31;1m" + "someText");

but it did not work. How do I achieve this?

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
Kalimah
  • 11,217
  • 11
  • 43
  • 80
  • See this: http://stackoverflow.com/questions/4897349/android-coloring-part-of-a-string-using-textview-settext – live-love Aug 05 '15 at 13:57

4 Answers4

32

this will help u

Spannable WordtoSpan = new SpannableString("I know just how to whisper");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 13, 
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(WordtoSpan);
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
4

You're looking for TextAppearanceSpan and 'SpannableString' To be more clear workflow is as follow

  1. Create SpannableString from your source String
  2. Create TextAppearanceSpan and set it via call to setSpan method on SpannableString
  3. Call textView.setText method with SpannableString as argument
Nikolay Ivanov
  • 8,897
  • 3
  • 31
  • 34
2

You can also use HTML like in the following example:

string = "<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>";
textView.setText(Html.fromHtml(string));

Without using additional variable (one-line solution):

textView.setText(Html.fromHtml("<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>"));

It is quite easy and understandable solution :)

Marek
  • 3,935
  • 10
  • 46
  • 70
2

I know I'm a bit late for the party but I think this is going to help future visitors out.

You might wanna set partial text colors on the layout XML instead of using Java code, so based on previous answers on this thread I've created a small class that does the trick.

1 - First let's create our component

package yourpackagehere.component;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import yourpackagehere.R;

public class FontSpannableTextView extends TextView {

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

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

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

    private void setColorPartialString(Context context, AttributeSet attrs) {
        if (isInEditMode()) {
            return;
        }
        String partialText = null;
        int partialTextColor = Integer.MIN_VALUE;

        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontSpannableTextView);
            for (int i = 0; i < a.getIndexCount(); i++) {
                int attr = a.getIndex(i);
                switch (attr) {
                    case R.styleable.FontSpannableTextView_fontspannabletextview_partialText:
                        partialText = a.getString(attr);
                        break;
                    case R.styleable.FontSpannableTextView_fontspannabletextview_partialTextColor:
                        partialTextColor = a.getColor(attr, Color.BLACK);
                        break;
                }
            }
            a.recycle();
        }

        if (partialText != null && partialTextColor != Integer.MIN_VALUE) {
            String wholeText = getText().toString();
            Spannable spannable = new SpannableString(wholeText);
            spannable.setSpan(new ForegroundColorSpan(partialTextColor),
                    wholeText.indexOf(partialText),
                    wholeText.indexOf(partialText) + partialText.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            setText(spannable);
        } else {
            Log.e("YOURTAGHERE","You must provide both partialText and partialTextColor values");
        }
    }
}

2 - on attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FontSpannableTextView">
        <attr name="fontspannabletextview_partialText" format="string" />
        <attr name="fontspannabletextview_partialTextColor" format="color" />
    </declare-styleable>
</resources>

3 - Let's use it in our test layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <yourpackagehere.component.FontSpannableTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" <!-- Hello world! -->
        android:layout_margin="25dp"
        app:fontspannabletextview_partialText="@string/world" <!-- world! -->
        app:fontspannabletextview_partialTextColor="@color/tutorial_yellow"
        android:textSize="40sp"
        />

</LinearLayout>

Example:

enter image description here

Paulo Miguel Almeida
  • 2,114
  • 31
  • 36
  • This is an elegant solution. I have been working on android since a decade but even in 2020 this seems to be a major problem with `TextView` in android. – JaydeepW Mar 16 '20 at 09:04