在输入edittext时更改特定单词的文本颜色

时间:2017-03-14 15:51:27

标签: android android-edittext

我想更改我在edittext中输入的特定单词的颜色。但是这段代码只改变了一次。当我键入另一个功能时,它不会改变颜色。

public class Controller implements Initializable {
    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        // TODO Auto-generated method stub
    }
}

1 个答案:

答案 0 :(得分:5)

indexOf将始终提供第一个找到的值的索引,因此您需要遍历字符串并查找所有function字符串并在其上应用span并从特定索引中搜索{{3 }}

// a single object to apply on all strings 
ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);    
String s1 = s.toString();
int in=0; // start searching from 0 index

// keeps on searching unless there is no more function string found 
while ((in = s1.indexOf(FUNCTION,in)) >= 0) {
    s.setSpan(
        fcs,
        in,
        in + FUNCTION.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    // update the index for next search with length
    in += FUNCTION.length();
}

为避免与div divide匹配,您需要使用regex \\b \\b表示字边界,以避免divdivide匹配{1}}

ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);    
String s1 = s.toString();

Pattern pattern = Pattern.compile("\\b"+FUNCTION+"\\b");
Matcher matcher = pattern.matcher(s1);

// keeps on searching unless there is no more function string found 
while (matcher.find()) {
    s.setSpan(
            fcs,
            matcher.start(),
            matcher.end(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}