Reputation: 1517
I ALREADY know there are many questions asking the same thing, but they don't work for me. Here is the code (I use the code to color a text part in a EditText) -
et_note.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (textCC.contains("sample_text")) {
String syntaxText = "sample_text";
int ofe = textCC.indexOf(syntaxText, 0);
int nextOfe = textCC.indexOf(syntaxText, ofe);
for (int ofs = 0; ofs < textCC.length() && ofe != -1 && nextOfe != -1; ofs = nextOfe + 1) {
ofe = textCC.indexOf(syntaxText, ofs);
nextOfe = textCC.indexOf(syntaxText, ofe + 1);
if (ofe == -1 || nextOfe == -1) {
break;
} else {
Spannable WordtoSpan = new SpannableString(et_note.getText());
WordtoSpan.setSpan(new ForegroundColorSpan(0xFF00FF00), ofe, nextOfe + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
et_note.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
}
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
It gives Stack Overflow error.
Answers that work but are not suitable -
1) Add et_note.removeTextChangedListener(this)
before the code and add et_note.addTextChangedListener(this)
after the code - This one works but NOT properly and the app becomes VERY slow.
Any other ways that will help me? Thanks.
Upvotes: 0
Views: 178
Reputation: 1517
Thanks to CommonsWare, I found the answer. Just posting this answer to help others. This solved my problem -
Instead of this,
Spannable WordtoSpan = new SpannableString(et_note.getText());
WordtoSpan.setSpan(new ForegroundColorSpan(0xFF00FF00), ofe, nextOfe + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
et_note.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
I used this -
et_note.getText().setSpan(new ForegroundColorSpan(0xFF00FF00), ofe, nextOfe + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Upvotes: 1