我正在尝试实现类似于代码编辑器的东西,其中关键字会自动突出显示。我将有一个字符串数组,当用户键入文本并且它与字符串数组中的字符串匹配时,我想更改 editText 字符串的颜色和字体。我正在使用 addTextChangeListener 但整个 editText 的文本发生了变化。我只想突出显示匹配的单词。我知道我必须使用可扩展的字符串,但代码崩溃了。任何人都可以帮助我通过 addTextChangedListener() 正确使用可扩展字符串吗? 这是我的代码:
editText.addTextChangedListener(new TextWatcher() {
private SpannableString spanString;
private ForegroundColorSpan span;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
spanString = new SpannableString(s);
span = new ForegroundColorSpan(Color.YELLOW);
spanString.setSpan(span, start, start + count, 0);
}
@Override
public void afterTextChanged(Editable s) {
int beginIdx = spanString.getSpanStart(s);
int endIdx = spanString.getSpanEnd(s);
if(s.subSequence(beginIdx, endIdx).equals("for"))
{
editText.setText(spanString, EditText.BufferType.SPANNABLE);
}
spanString.removeSpan(span);
span = null;
spanString = null;
}
});
最佳答案
ms1996 我知道您正在尝试创建 IDE。要突出显示代码代码的语法,您应该使用 spannable String 或使用任何库来使其更容易。此外,您可以尝试以下代码:
I created simple code for highlight syntax in EditText. First i created a HashMap to store keywords and colors.
Map<String,Integer> map = new HashMap<>();
map.put("public",Color.CYAN);
map.put("void", Color.BLUE);
map.put("String",Color.RED);
然后我为 EditText 添加了一个 TextWatcher。在 afterTextChanged 方法中,我使用以下代码为每个关键字设置颜色,
........
@Override
public void afterTextChanged(Editable editable) {
String string = editable.toString();
String[] split = string.split("\\s");
for(int i = 0 ; i < split.length ; i++){
String s = split[i];
if(map.containsKey(s)){
int index = string.indexOf(s);
int color = map.get(s);
editable.setSpan(new ForegroundColorSpan(color),
index,
index + s.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
关于java - 如何在 addTextChangedListener 中使用可扩展字符串来更改 editText 子字符串的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65016809/