如何在TextView中更改某些字符颜色

时间:2014-08-29 01:47:35

标签: android textview

我知道我可以用TextView改变Spannable部分的颜色,我用它来改变文本中每个字符'e'的颜色。但我得到了这个错误:

  

java.lang.IndexOutOfBoundsException:setSpan(55 ... 56)结束   长度0

我的代码:

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);
    }
}

任何方式?

2 个答案:

答案 0 :(得分:2)

试试这个:

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

来自https://stackoverflow.com/a/6094346/3922891

的原创想法

答案 1 :(得分:1)

我遇到了同样的问题。以下是我的代码。您可以在代码中使用此示例:

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