I am trying to implement something similar to a code editor where keywords are automatically highlighted. I am going to have a string array and I want to change the color and font of the editText string when the user types the text and it matches a string from the string array. I am using the addTextChangeListener but the text of the whole editText changes. I want just the matched word to be highlighted.I understand I have to use spannable strings but the code crashes. Can anyone help me with the correct usage of spannable strings with addTextChangedListener() ? Here is my code:
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;
}
});