我想更改我在edittext中输入的特定单词的颜色。但是这段代码只改变了一次。当我键入另一个功能时,它不会改变颜色。
public class Controller implements Initializable {
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
}
答案 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
表示字边界,以避免div
与divide
匹配{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);
}