0

I want to change the color of some part of text in EditText. I am trying following code, but it is not working.

SpannableStringBuilder ssb=new SpannableStringBuilder(expression);
ForegroundColorSpan fcs=new ForegroundColorSpan(Color.rgb(181,1,1));
ssb.setSpan(fcs,startIndex,endIndex,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
expressionEditText.setText(ssb);
expressionTextView.setText(ssb);

startIndex and endIndex are the indices in the expression for which the color needs to be changed.

This code works fine for the 'expressionTextView' but not for 'expressionEditText'.

xml part:

<EditText
android:id="@+id/expression_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_above="@id/expression_text_view"
android:gravity="bottom|end"
android:includeFontPadding="false"
android:textSize="45sp"
android:background="@android:color/transparent"
android:inputType="text"/>

<TextView
android:id="@+id/expression_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:gravity="right"
android:textSize="50sp"/>

example:

expression="I want color to be changed";
startIndex=2;
endIndex=5;

In expressionTextView "wan" color will be the specified color. In expressionEditText there will not be any color change.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

This is very simple.

As i answered before in this question.

You can achieve this by the following code, which i use always. I tried to make this method as simple as i could. You have to pass just your Editext and TextToHighLight in below method.

If you require clickable span you can go to my answer. Feel free to ask in comment if you need TextWatcher too.

public void setHighLightedText(EditText editText, String textToHighlight) {
    String tvt = editText.getText().toString();
    int ofe = tvt.indexOf(textToHighlight, 0);
    Spannable WordtoSpan = new SpannableString(editText.getText());

    for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {


        ofe = tvt.indexOf(textToHighlight, ofs);
        if (ofe == -1)
            break;
        else {
            WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            editText.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
        }
    }
}
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212