android EditText高亮显示文本中的多个单词 [英] android EditText highlight multiple words in the text

查看:88
本文介绍了android EditText高亮显示文本中的多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在EditText的文本中搜索了一些单词.经过一番逻辑,我得到了这些词的索引.索引存储在arrayList>中.

I have searched some words in the text of a EditText. After some logic, I get the index of these words. The indices are stored in an arrayList>.

然后我使用此功能突出显示这些单词的颜色.

Then I used this function to highlight the color of these words.

    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,但是仍然只有一个单词突出显示.有人可以帮忙看看这里有什么问题吗?谢谢.

However, only the first word was highlight even though the loop was executed by the times of number of words. I tried to replace the EditText with TextView, but still only have one word highlight. Can someone help see what's wrong here? Thank you.

推荐答案

这就是我正在使用的.

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

这篇关于android EditText高亮显示文本中的多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆