Skip to content

Instantly share code, notes, and snippets.

@mrmike
Last active November 30, 2023 00:20
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrmike/77fe2a6a357e78108115 to your computer and use it in GitHub Desktop.
Save mrmike/77fe2a6a357e78108115 to your computer and use it in GitHub Desktop.
Remove extra space from Android spannable
private void setText(String html) {
SpannableStringBuilder spanned = (SpannableStringBuilder) Html.fromHtml(html);
spanned = trimSpannable(spanned);
mTextView.setText(spanned, TextView.BufferType.SPANNABLE);
}
private SpannableStringBuilder trimSpannable(SpannableStringBuilder spannable) {
checkNotNull(spannable);
int trimStart = 0;
int trimEnd = 0;
String text = spannable.toString();
while (text.length() > 0 && text.startsWith("\n")) {
text = text.substring(1);
trimStart += 1;
}
while (text.length() > 0 && text.endsWith("\n")) {
text = text.substring(0, text.length() - 1);
trimEnd += 1;
}
return spannable.delete(0, trimStart).delete(spannable.length() - trimEnd, spannable.length());
}
@bbincybbaby
Copy link

this not removing space before text

@baisaaRules
Copy link

thanks.. its is awsom'

@AdrianLxM
Copy link

Doesn't that have a problem when it deletes from front and from the end?
spannable.length() will still have the old value when the new one is actually shorter already from having removed from the start.

@robindanielk
Copy link

Works perfectly...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment