我在 EditText 的文本中搜索了一些词。经过一些逻辑,我得到了这些词的索引。索引存储在 arrayList> 中。
然后我就用这个函数来高亮这些文字的颜色。
public void changeColor(EditText et, ArrayList<ArrayList<Integer>> arr) {
Spannable wordtoSpan = new SpannableString(et.getText());
if (arr==null) return;
for (int i=0; i<arr.size(); i++){
wordtoSpan.setSpan(new BackgroundColorSpan(Color.BLUE), arr.get(i).get(0),
arr.get(i).get(1), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
et.setText(wordtoSpan, TextView.BufferType.SPANNABLE);
System.out.println("i'm changing color now");
}
}
然而,即使循环执行了单词数的倍数,也只有第一个单词被高亮显示。 我试图用 TextView 替换 EditText,但仍然只有一个单词突出显示。 有人可以帮忙看看这里出了什么问题吗?谢谢。
最佳答案
这似乎是正确的,但最好将您的代码替换为
public void changeColor(EditText et, ArrayList<ArrayList<Integer>> arr) {
Spannable wordtoSpan = new SpannableString(et.getText());
if (arr==null) return;
for (int i=0; i<arr.size(); i++){
wordtoSpan.setSpan(new BackgroundColorSpan(Color.BLUE), arr.get(i).get(0),
arr.get(i).get(1), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
System.out.println("i'm changing color now");
}
et.setText(wordtoSpan);
}
如果在这个改变之后,你的问题仍然存在,我认为它可能与你在“arr”中的字符串索引有关
关于java - android EditText高亮文本中的多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22890075/