Let´s say I make a comment like this:
Hi Andrea check this out..... In that comment I want to highlight Andrea, but whenever I change the value of Andrea or when I delete one character of the word the span changes, the problem is that I´m using spannableString.setSpan(new StyleSpan(Typeface.BOLD), indexOfAt, highlightName.length() + indexOfAt, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
, which Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
accepts words in the middle and deletion of words, how can I remove the span when the user changes the word or delete a character of the word?
To delete a text span you will still need to double click into the text element, select the portion you want to remove and delete.
Spans are powerful markup objects that you can use to style text at a character or paragraph level. By attaching spans to text objects, you can change text in a variety of ways, including adding color, making the text clickable, scaling the text size, and drawing text in a customized way.
If you are using the SpannableString
you have to recreate the whole thing on every change.
You can remove spans but you cannot change the source (the comment) because SpannableString
source text is immutable.
I suggest on every change of the comment you create the SpannableString
, look for names and tag them, then if the comment changes you repeat the same thing with a new SpannableString
. There will be no performance problems because the comments are small in size.
If you want to have a mutable object you can use the SpannableStringBuilder
but it's more complicated and there is no need for it.
You need to watch for Text change on the edit text.
Assuming the EditText
, you are using is named as commentEditText
commentEditText.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) {
}
@Override
public void afterTextChanged(Editable editable) {
String comment = editable.toString();
if (comment.indexOf('@') != -1) {
//Asumming the name string
String name = "Andrea";
int atIndex = comment.indexOf('@');
int endIndex = atIndex + name.length() + 1;
if (endIndex == -1 || endIndex > editable.length()) {
endIndex = editable.length();
}
if (comment.toLowerCase().contains(name.toLowerCase())) {
editable.setSpan(new StyleSpan(Typeface.BOLD), atIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
StyleSpan[] spannable = editable.getSpans(atIndex, endIndex, StyleSpan.class);
if (spannable != null && spannable.length > 0) {
for (int i = 0; i < spannable.length; i++) {
editable.removeSpan(spannable[i]);
}
}
}
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With