1

I know that I can change color of the part of TextView with Spannable, I use this for changing color of every character 'e' in text. But I got this error:

java.lang.IndexOutOfBoundsException: setSpan (55 ... 56) ends beyond length 0

My code:

aye="My Text has been written today";
SpannableString spantext=new SpannableString(aye);
for (int i=0;i<aye.length();i++) {
    if (aye.contains("e")) {
        a+=aye.indexOf("e", a)+1;
        spantext.setSpan(new ForegroundColorSpan(Color.RED), a, a+1, 0);
        holder.tv_arabic.setText(spantext);
    }
}

Any way?

Artem Mostyaev
  • 3,874
  • 10
  • 53
  • 60
ali
  • 25
  • 1
  • 5
  • do you already reference that? http://stackoverflow.com/a/16335416/3247356 that link comments have solved "IndexOutOfBoundsException". – B M Aug 29 '14 at 03:08

2 Answers2

4

Try this:

aye="My Text has been written today";
String newText = aye.replace("e", "<font color=#FF0000>e</font>");
holder.tv_arabic.setText(Html.fromHtml(newText));

Original idea from https://stackoverflow.com/a/6094346/3922891

Community
  • 1
  • 1
PrivatMamtora
  • 2,072
  • 2
  • 19
  • 29
2

I have faced the same problem.Following is my code.You can follow this example in your code:

String aye = "My Text has been written today";
        String ayeTemp = "My Text has been written today";

        ArrayList<Integer> positionInt = new ArrayList<>();
        for (int i = 0; i < ayeTemp.length(); i++) {
            if (ayeTemp.contains("e")) {
                if (positionInt.size() == 0) {
                    positionInt.add(ayeTemp.indexOf("e"));
                } else {
                    positionInt.add(positionInt.get(positionInt.size() - 1) + ayeTemp.indexOf("e") + 1);
                }
                ayeTemp = ayeTemp.substring(ayeTemp.indexOf("e") + 1, ayeTemp.length() - 1);
            } else {
                break;
            }
        }
        Spannable wordtoSpan = new SpannableString(aye);
        for (int i = 0; i < positionInt.size(); i++) {
            wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), positionInt.get(i), positionInt.get(i) + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        holder.tv_arabic.setText(wordtoSpan);

like this

Lips_coder
  • 686
  • 1
  • 5
  • 17