For a long time i been confused by the setSpan
as it looks so easy but not always working as expected
In my last attempt i am trying to setSpan
to recognized patterns.
When user starts typing "5 kilo toma" the "5 kilo" will be highlighted.
I used the next code to do that as part of the TextWatcher
listener
@Override
public void afterTextChanged(Editable s) {
String quantity = mAutoCompleteAdapter.getQuantity();
if (!quantity.isEmpty()) {
int index = mAutoCompleteAdapter.getQuantityIndex();
final StyleSpan styleSpan = new StyleSpan( Typeface.BOLD_ITALIC );
s.setSpan( styleSpan, index, index + quantity.length(), Spanned.SPAN_MARK_MARK );
}
}
This is working correctly (basic testing)
But if i start deleting the text to read "5 kil", the setSpan
does not refresh to normal when pattern no longer detected
So i was thinking, perhaps the setSpan
is kept in memory or something and i need to set entire string span every time. So i tried the next code:
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
String quantity = mAutoCompleteAdapter.getQuantity();
int index = 0;
if (!quantity.isEmpty()) {
index = mAutoCompleteAdapter.getQuantityIndex();
StyleSpan styleSpan = new StyleSpan( Typeface.BOLD_ITALIC );
s.setSpan( styleSpan, index, index + quantity.length(), Spanned.SPAN_MARK_MARK );
}
StyleSpan styleSpanNormal = new StyleSpan( Typeface.NORMAL );
s.setSpan( styleSpanNormal, index + quantity.length(), s.length(), Spanned.SPAN_MARK_MARK );
}
}
But still not working correctly