我知道我可以用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);
}
}
任何方式?
答案 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));
的原创想法
答案 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);