本文介绍了如何为edittext实现一个简单的语法高亮方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个涉及编码的应用程序,我需要编辑文本来识别键入的单词是否为某事物,然后根据它是否已注册为彩色,它将为该单词着色。这是我想要做的,当用户键入并输入功能时,我希望它自动突出显示。同样适用于任何其他'功能'字样,'()','''以及用户输入的许多其他字词。
I am making an app that involves coding and I need edittext to recognize if the word typed was 'something' then depending if it is registered to be colored, it will color the word. Here is what I want to do, when the user is typing and types 'function' I want it to automatically highlight. Same goes to any other 'function' word, '()', ' " ', and many other words the user types.
推荐答案
您可以使用来完成此操作:
You can accomplish this by using a TextWatcher like so:
editText.addTextChangedListener(new TextWatcher() {
final String FUNCTION = "function";
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
int index = s.toString().indexOf(FUNCTION);
if (index >= 0) {
s.setSpan(
new ForegroundColorSpan(Color.CYAN),
index,
index + FUNCTION.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
});
这篇关于如何为edittext实现一个简单的语法高亮方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!