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.
Asked
Active
Viewed 1,834 times
6
-
3Don't use `==` to compare value of Strings, even in example. Use `equals` instead. – Pshemo Dec 18 '13 at 21:30
-
== Should be used only to compare reference. To compare values, use string1.equalsIgnoreCase(string2) method – Prem Dec 18 '13 at 21:33
-
Does this mean I can use == if I compare it to values? And if I don't do I just put = ? – user3055552 Dec 18 '13 at 21:44
1 Answers
8
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);
}
}
});

Krylez
- 17,414
- 4
- 32
- 41
-
I really appreciate for you taking your time in making this example but I tried to use it and when I start typing the word is not highlighted. – user3055552 Dec 18 '13 at 22:42
-
1Never mind it works perfectly all I changed was if (index >= 0) and now it works like a charm!! THANKS!! – user3055552 Dec 18 '13 at 22:48
-
1You're welcome and thanks for finding the mistake (fixed now). Note that this will only catch the first occurrence of the word, but it's not hard to figure out how to highlight all occurrences. – Krylez Dec 18 '13 at 23:02
-
Is there a way to get rid of the highlighting when I write between {} ? – user3055552 Dec 18 '13 at 23:07